diff options
author | Michael Lando <ml636r@att.com> | 2018-03-04 14:53:33 +0200 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2018-03-07 13:19:05 +0000 |
commit | a5445100050e49e83f73424198d73cd72d672a4d (patch) | |
tree | cacf4df817df31be23e4e790d1dda857bdae061e /catalog-be/src/main/java/org | |
parent | 51157f92c21976cba4914c378aaa3cba49826931 (diff) |
Sync Integ to Master
Change-Id: I71e3acc26fa612127756ac04073a522b9cc6cd74
Issue-ID: SDC-977
Signed-off-by: Gitelman, Tal (tg851x) <tg851x@intl.att.com>
Diffstat (limited to 'catalog-be/src/main/java/org')
378 files changed, 65602 insertions, 57492 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java new file mode 100644 index 0000000000..eed347f781 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.api; + +import org.javatuples.Pair; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; + +import java.util.List; + +public interface AuditEventFactory { + + String getLogMessage(); + AuditingGenericEvent getDbEvent(); + List<Pair<String, String>> getQueryParams(); + + //TODO remove together with ES related code + String getAuditingEsType(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java deleted file mode 100644 index b6cd4320f4..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.auditing.api; - -import java.util.EnumMap; - -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - -public interface IAuditingManager { - void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields); -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java new file mode 100644 index 0000000000..b68ee0db23 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuthEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAuthRequestEventFactory extends AuditBaseEventFactory { + + private final static String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\""; + + final private AuthEvent event; + + public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus) { + super(AuditingActionEnum.AUTH_REQUEST); + event = new AuthEvent(getAction().getName(), commonFields, authUser, authUrl, realm, authStatus); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getUrl(), event.getUser(), event.getAuthStatus(), event.getRealm()); + } + + + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java new file mode 100644 index 0000000000..8636c1b01d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.apache.commons.lang.StringUtils; +import org.javatuples.Pair; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.api.Constants; + +import java.util.Collections; +import java.util.List; + +public abstract class AuditBaseEventFactory implements AuditEventFactory { + + //TODO imanzon: Check if requestId and serviceInstanceId fields are required for all tables. + //Currently they are included even if they ahs null value. If they should not appear then + //createTable code should be updated so that they need to be removed from the tables + private AuditingActionEnum action; + + public AuditBaseEventFactory(AuditingActionEnum action) { + this.action = action; + } + + public AuditingActionEnum getAction() { + return action; + } + + public static String buildUserNameExtended(User user) { + if (user == null) { + return null; + } + + StringBuilder builder = new StringBuilder(); + appendIfNotEmpty(user.getUserId(), builder); + + String firstName = replaceNullNameWithEmpty(user.getFirstName()); + String lastName = replaceNullNameWithEmpty(user.getLastName()); + + if (appendIfNotEmpty(firstName, builder)) { + appendIfNotEmpty(lastName, builder, " "); + } + else { + appendIfNotEmpty(lastName, builder); + } + appendIfNotEmpty(user.getEmail(), builder); + appendIfNotEmpty(user.getRole(), builder); + + return builder.toString(); + } + + private static boolean appendIfNotEmpty(String value, StringBuilder builder) { + return appendIfNotEmpty(value, builder, ", "); + } + + protected static boolean appendIfNotEmpty(String value, StringBuilder builder, String delimiter) { + if (StringUtils.isEmpty(value)) { + return false; + } + addDelimiterIfNeeded(builder, delimiter); + builder.append(value); + return true; + } + + private static void addDelimiterIfNeeded(StringBuilder builder, String delimiter) { + if (builder.length() > 0) { + builder.append(delimiter); + } + } + + protected static String buildUserName(User user) { + if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) { + return Constants.EMPTY_STRING; + } + StringBuilder sb = new StringBuilder(); + String firstName = replaceNullNameWithEmpty(user.getFirstName()); + if (!firstName.isEmpty()) { + sb.append(firstName); + sb.append(" "); + } + String lastName = replaceNullNameWithEmpty(user.getLastName()); + if (!lastName.isEmpty()) { + sb.append(lastName); + } + sb.append("(").append(user.getUserId()).append(")"); + return sb.toString(); + } + + public static String buildValue(String value) { + if (value == null) { + return Constants.EMPTY_STRING; + } + return value; + } + + protected static String replaceNullNameWithEmpty(String name) { + if (name != null && !name.trim().contains(Constants.NULL_STRING)) { + return name; + } + return Constants.EMPTY_STRING; + } + + @Override + //TODO implement in derived classes for ci testing + public List<Pair<String, String>> getQueryParams() { + return Collections.emptyList(); + } + + @Override + public String getAuditingEsType() { + return this.action.getAuditingEsType(); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java new file mode 100644 index 0000000000..01c82e88da --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.model.ConsumerDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditConsumerEventFactory extends AuditBaseEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" ECOMP_USER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + private final ConsumerEvent event; + + public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, ConsumerDefinition ecompUser) { + super(action); + event = new ConsumerEvent(getAction().getName(), commonFields, buildConsumerName(ecompUser), buildUserName(modifier)); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + + + static String buildConsumerName(ConsumerDefinition consumer) { + StringBuilder ecompUser = new StringBuilder(); + if (consumer != null) { + appendIfNotEmpty(consumer.getConsumerName(), ecompUser, ","); + appendIfNotEmpty(consumer.getConsumerSalt(), ecompUser, ","); + appendIfNotEmpty(consumer.getConsumerPassword(), ecompUser, ","); + } + return ecompUser.toString(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java new file mode 100644 index 0000000000..95dddec3ad --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; + +public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory { + private static final String LOG_STR = "ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ID = \"%s\"" + + " OPERATIONAL_ENVIRONMENT_NAME = \"%s\" OPERATIONAL_ENVIRONMENT_TYPE = \"%s\" TENANT_CONTEXT = \"%s\""; + + private final EcompOperationalEnvironmentEvent event; + + public AuditEcompOpEnvEventFactory(AuditingActionEnum action, String operationalEnvironmentId, String operationalEnvironmentName, + String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) { + super(action); + event = new EcompOperationalEnvironmentEvent(getAction().getName(), operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, operationalEnvironmentAction, tenantContext); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getOperationalEnvironmentAction()), + buildValue(event.getOperationalEnvironmentId()), buildValue(event.getOperationalEnvironmentName()), + buildValue(event.getOperationalEnvironmentType()), buildValue(event.getTenantContext())); + } + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java new file mode 100644 index 0000000000..3400016ff0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditArtifactResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCertificationResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCreateUpdateResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeRequestResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditResourceEventFactoryMananger { + + + public static AuditBaseEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + AuditBaseEventFactory factory = null; + + switch (action) { + case IMPORT_RESOURCE: + factory = new AuditImportResourceAdminEventFactory(commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + break; + case CREATE_RESOURCE: + case UPDATE_RESOURCE_METADATA: + factory = new AuditCreateUpdateResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING); + break; + case CHECKIN_RESOURCE: + case CHECKOUT_RESOURCE: + case UNDO_CHECKOUT_RESOURCE: + case CERTIFICATION_REQUEST_RESOURCE: + case START_CERTIFICATION_RESOURCE: + case CERTIFICATION_SUCCESS_RESOURCE: + case FAIL_CERTIFICATION_RESOURCE: + case CANCEL_CERTIFICATION_RESOURCE: + factory = new AuditCertificationResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + case ARTIFACT_UPLOAD: + case ARTIFACT_DELETE: + case ARTIFACT_METADATA_UPDATE: + case ARTIFACT_PAYLOAD_UPDATE: + case ARTIFACT_DOWNLOAD: + factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; +// case DOWNLOAD_ARTIFACT: +// factory = new AuditDownloadArtifactExternalApiEventFactory(commonFields, String resourceType, String resourceName, +// String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, +// String invariantUuid, User modifier, String artifactData); +// break; + case DISTRIBUTION_STATE_CHANGE_REQUEST: + factory = new AuditDistStateChangeRequestResourceAdminEventFactory(commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + case DISTRIBUTION_STATE_CHANGE_APPROV: + case DISTRIBUTION_STATE_CHANGE_REJECT: + factory = new AuditDistStateChangeResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + default: + throw new UnsupportedOperationException(); + } + return factory; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java index ed0fd6de0e..69c4eb82a0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java @@ -24,276 +24,301 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; class AuditingLogFormatConstants { - private AuditingLogFormatConstants() {} - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME}; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, - AuditingFieldsKeysEnum.AUDIT_STATUS - }; - - static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS - }; - - static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT - }; - - static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE - - }; - - static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_USER_UID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_UID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_AUTH_URL, - AuditingFieldsKeysEnum.AUDIT_AUTH_USER, - AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, - AuditingFieldsKeysEnum.AUDIT_AUTH_REALM - }; - - static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, - AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, - AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_DETAILS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, - AuditingFieldsKeysEnum.AUDIT_USER_AFTER, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - - AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; + private AuditingLogFormatConstants() {} + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME}; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, +// AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, - check if required + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID + }; + + static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, + AuditingFieldsKeysEnum.AUDIT_STATUS + }; + + static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS + }; + + static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT + }; + + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE + + }; + + static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_USER_UID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_UID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_AUTH_URL, + AuditingFieldsKeysEnum.AUDIT_AUTH_USER, + AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, + AuditingFieldsKeysEnum.AUDIT_AUTH_REALM + }; + + static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, + AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, + AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_DETAILS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, + AuditingFieldsKeysEnum.AUDIT_USER_AFTER, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static AuditingFieldsKeysEnum[] ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE, + AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static AuditingFieldsKeysEnum[] EXTERNAL_ACTIVATE_SERVICE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java index 8fb5c4116e..ee4b70c0f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.auditing.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.Formatter; -import java.util.Locale; - import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -34,240 +28,269 @@ import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Formatter; +import java.util.Locale; +import java.util.Map; + public class AuditingLogFormatUtil { - // When adding any new fields here, please keep the convention <fieldName>= - // <value>, with the space between them. - private static Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class.getName()); - - // This is the key by which audit marker is recognized in logback.xml - private static String AUDIT_MARKER_STR = "AUDIT_MARKER"; - - public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); - - protected static void logAuditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - log.trace("logAuditEvent - start"); - - try { - - // Common fields - String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); - Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - String status = null; - if (statusObj != null) { - status = String.valueOf(statusObj); - } - String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - - AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action); - StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType); - String formattedString = formattedEvent.toString(); - - // This is the only way to fix DE166225 without major refactoring, - // after it was previously agreed with Ella that activity type will - // be the method name. - - if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) { - HttpRequestAuthentication(formattedString); - } else { - log.info(auditMarker, formattedString); - } - } catch (Exception e) { - log.debug("unexpected error occurred: {}", e.getMessage(), e); - - } finally { - formatter.close(); - log.trace("logAuditEvent - end"); - } - - } - - private static void HttpRequestAuthentication(String formattedString) { - log.info(auditMarker, formattedString); - } - - private static StringBuilder getFormattedEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) { - - StringBuilder formattedString = new StringBuilder(); - - switch (auditEventType) { - case ADD_USER: - case DELETE_USER: - case UPDATE_USER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields); - - break; - case USER_ACCESS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_REGISTER: - case DISTRIBUTION_UN_REGISTER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields); - break; - case UPDATE_RESOURCE_METADATA: - case CREATE_RESOURCE: - case IMPORT_RESOURCE: - ArrayList<AuditingFieldsKeysEnum> createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); - createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); - if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) { - createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE); - } - AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100]; - createResourceArray = createResourceList.toArray(createResourceArray); - formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields); - break; - case CHECKIN_RESOURCE: - case CHECKOUT_RESOURCE: - case UNDO_CHECKOUT_RESOURCE: - case CERTIFICATION_REQUEST_RESOURCE: - case START_CERTIFICATION_RESOURCE: - case CERTIFICATION_SUCCESS_RESOURCE: - case FAIL_CERTIFICATION_RESOURCE: - case CANCEL_CERTIFICATION_RESOURCE: - ArrayList<AuditingFieldsKeysEnum> checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); - checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); - checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); - AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100]; - checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray); - String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); - if (comment == null || comment.equals(Constants.NULL_STRING)) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING); - } - formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields); - break; - case ARTIFACT_UPLOAD: - case ARTIFACT_DELETE: - case ARTIFACT_METADATA_UPDATE: - case ARTIFACT_PAYLOAD_UPDATE: - case ARTIFACT_DOWNLOAD: - ArrayList<AuditingFieldsKeysEnum> artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ; - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); - artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case DOWNLOAD_ARTIFACT: - ArrayList<AuditingFieldsKeysEnum> downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case DISTRIBUTION_STATE_CHANGE_REQUEST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields); - break; - case DISTRIBUTION_STATE_CHANGE_APPROV: - case DISTRIBUTION_STATE_CHANGE_REJECT: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields); - break; - case CREATE_DISTRIBUTION_TOPIC: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_KEY_TO_TOPIC_ACL: - case REMOVE_KEY_FROM_TOPIC_ACL: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_STATUS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_NOTIFY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields); - break; - case DISTRIBUTION_DEPLOY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields); - break; - case GET_UEB_CLUSTER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields); - break; - case DISTRIBUTION_ARTIFACT_DOWNLOAD: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields); - break; - case AUTH_REQUEST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_ECOMP_USER_CREDENTIALS: - case GET_ECOMP_USER_CREDENTIALS: - case DELETE_ECOMP_USER_CREDENTIALS: - case UPDATE_ECOMP_USER_CREDENTIALS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_CATEGORY: - case ADD_SUB_CATEGORY: - case ADD_GROUPING: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields); - break; - case GET_USERS_LIST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields); - break; - case GET_CATEGORY_HIERARCHY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields); - break; - case GET_ASSET_LIST: - case GET_FILTERED_ASSET_LIST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields); - break; - case GET_ASSET_METADATA: - case GET_TOSCA_MODEL: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields); - break; - case ARTIFACT_UPLOAD_BY_API: - case ARTIFACT_DELETE_BY_API: - case ARTIFACT_UPDATE_BY_API: - ArrayList<AuditingFieldsKeysEnum> uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case CREATE_RESOURCE_BY_API: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields); - break; - case CHANGE_LIFECYCLE_BY_API: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields); - break; - default: - break; - } - - return formattedString; - } - - private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - StringBuilder formattedString = new StringBuilder(); - for (int i = 0; i < sortedFieldsArray.length; i++) { - AuditingFieldsKeysEnum key = sortedFieldsArray[i]; - - Object fieldVal = auditingFields.get(key); - if (fieldVal != null) { - formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\""); - if (i < sortedFieldsArray.length - 1) { - formattedString.append(" "); - } - } - } - return formattedString; - } - - protected static String getModifier(String modifierName, String modifierUid) { - if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) { - return Constants.EMPTY_STRING; - } - StringBuilder sb = new StringBuilder(); - if (modifierName != null) { - sb.append(modifierName); - } - sb.append("(").append(modifierUid).append(")"); - return sb.toString(); - } - - protected static String getUser(String userData) { - StringBuilder sb = new StringBuilder(); - sb.append(userData); - return sb.toString(); - } + // When adding any new fields here, please keep the convention <fieldName>= + // <value>, with the space between them. + private static final Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class); + + // This is the key by which audit marker is recognized in logback.xml + private static String AUDIT_MARKER_STR = "AUDIT_MARKER"; + + public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); + + protected static String logAuditEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) { + + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + log.trace("logAuditEvent - start"); + + String formattedString = ""; + + try { + + // Common fields + String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); + Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + String status = null; + if (statusObj != null) { + status = String.valueOf(statusObj); + } + String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); + String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); + + AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action); + StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType); + formattedString = formattedEvent.toString(); + + // This is the only way to fix DE166225 without major refactoring, + // after it was previously agreed with Ella that activity type will + // be the method name. + + if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) { + HttpRequestAuthentication(formattedString); + } else { + log.info(auditMarker, formattedString); + } + } catch (Exception e) { + log.debug("unexpected error occurred: {}", e.getMessage(), e); + + } finally { + formatter.close(); + log.trace("logAuditEvent - end"); + } + return formattedString; + + } + + protected static void logAuditEvent(final String formattedString) { + log.trace("logAuditEvent - start"); + log.info(auditMarker, formattedString); + log.trace("logAuditEvent - end"); + } + + + private static void HttpRequestAuthentication(String formattedString) { + log.info(auditMarker, formattedString); + } + + private static StringBuilder getFormattedEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) { + + StringBuilder formattedString = new StringBuilder(); + + switch (auditEventType) { + case ADD_USER: + case DELETE_USER: + case UPDATE_USER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields); + + break; + case USER_ACCESS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_REGISTER: + case DISTRIBUTION_UN_REGISTER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields); + break; + case UPDATE_RESOURCE_METADATA: + case CREATE_RESOURCE: + case IMPORT_RESOURCE: + ArrayList<AuditingFieldsKeysEnum> createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); + createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); + if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) { + createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE); + } + AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100]; + createResourceArray = createResourceList.toArray(createResourceArray); + formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields); + break; + case CHECKIN_RESOURCE: + case CHECKOUT_RESOURCE: + case UNDO_CHECKOUT_RESOURCE: + case CERTIFICATION_REQUEST_RESOURCE: + case START_CERTIFICATION_RESOURCE: + case CERTIFICATION_SUCCESS_RESOURCE: + case FAIL_CERTIFICATION_RESOURCE: + case CANCEL_CERTIFICATION_RESOURCE: + ArrayList<AuditingFieldsKeysEnum> checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); + checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); + checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); + AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100]; + checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray); + String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); + if (comment == null || comment.equals(Constants.NULL_STRING)) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING); + } + formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields); + break; + case ARTIFACT_UPLOAD: + case ARTIFACT_DELETE: + case ARTIFACT_METADATA_UPDATE: + case ARTIFACT_PAYLOAD_UPDATE: + case ARTIFACT_DOWNLOAD: + ArrayList<AuditingFieldsKeysEnum> artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ; + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); + artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case DOWNLOAD_ARTIFACT: + ArrayList<AuditingFieldsKeysEnum> downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case DISTRIBUTION_STATE_CHANGE_REQUEST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields); + break; + case DISTRIBUTION_STATE_CHANGE_APPROV: + case DISTRIBUTION_STATE_CHANGE_REJECT: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields); + break; + case CREATE_DISTRIBUTION_TOPIC: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_KEY_TO_TOPIC_ACL: + case REMOVE_KEY_FROM_TOPIC_ACL: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_STATUS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_NOTIFY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields); + break; + case DISTRIBUTION_DEPLOY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields); + break; + case GET_UEB_CLUSTER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields); + break; + case DISTRIBUTION_ARTIFACT_DOWNLOAD: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields); + break; + case AUTH_REQUEST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_ECOMP_USER_CREDENTIALS: + case GET_ECOMP_USER_CREDENTIALS: + case DELETE_ECOMP_USER_CREDENTIALS: + case UPDATE_ECOMP_USER_CREDENTIALS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_CATEGORY: + case ADD_SUB_CATEGORY: + case ADD_GROUPING: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields); + break; + case GET_USERS_LIST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields); + break; + case GET_CATEGORY_HIERARCHY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields); + break; + case GET_ASSET_LIST: + case GET_FILTERED_ASSET_LIST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields); + break; + case GET_ASSET_METADATA: + case GET_TOSCA_MODEL: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields); + break; + case ARTIFACT_UPLOAD_BY_API: + case ARTIFACT_DELETE_BY_API: + case ARTIFACT_UPDATE_BY_API: + ArrayList<AuditingFieldsKeysEnum> uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case CREATE_RESOURCE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields); + break; + case CHANGE_LIFECYCLE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields); + break; + case ACTIVATE_SERVICE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_ACTIVATE_SERVICE_ARRAY, auditingFields); + break; + case CREATE_ENVIRONMENT: + case UPDATE_ENVIRONMENT: + case DELETE_ENVIRONMENT: + case UNKNOWN_ENVIRONMENT_NOTIFICATION: + case UNSUPPORTED_ENVIRONMENT_TYPE: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY, auditingFields); + break; + default: + break; + } + + return formattedString; + } + + private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, Map<AuditingFieldsKeysEnum, Object> auditingFields) { + StringBuilder formattedString = new StringBuilder(); + for (int i = 0; i < sortedFieldsArray.length; i++) { + AuditingFieldsKeysEnum key = sortedFieldsArray[i]; + + Object fieldVal = auditingFields.get(key); + if (fieldVal != null) { + formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\""); + if (i < sortedFieldsArray.length - 1) { + formattedString.append(" "); + } + } + } + return formattedString; + } + + protected static String getModifier(String modifierName, String modifierUid) { + if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) { + return Constants.EMPTY_STRING; + } + StringBuilder sb = new StringBuilder(); + if (modifierName != null) { + sb.append(modifierName); + } + sb.append("(").append(modifierUid).append(")"); + return sb.toString(); + } + + protected static String getUser(String userData) { + StringBuilder sb = new StringBuilder(); + sb.append(userData); + return sb.toString(); + } + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java index aa5afa4a8e..19eab0a409 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.auditing.impl; -import java.util.EnumMap; -import java.util.Map.Entry; - -import javax.annotation.Resource; - -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -39,99 +34,134 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -@Component("auditingManager") -public class AuditingManager implements IAuditingManager { - - private static Logger log = LoggerFactory.getLogger(AuditingManager.class.getName()); - - @Resource - private AuditingDao auditingDao; - @Autowired - private AuditCassandraDao cassandraDao; - - @Override - public void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - try { - boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit(); - if (disableAudit) { - return; - } - // Adding UUID from thread local - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid()); - - Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status)); - - // normalizing empty string values - US471661 - normalizeEmptyAuditStringValues(auditingFields); - - // Format modifier - formatModifier(auditingFields); - - // Format user - formatUser(auditingFields); - - // Logging the event - AuditingLogFormatUtil.logAuditEvent(auditingFields); - - // Determining the type of the auditing data object - AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType()); - ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType()); - if (!addRecordStatus.equals(ActionStatus.OK)) { - log.warn("Failed to persist auditing event: {}", addRecordStatus.name()); - } - - AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields); - if (recordForCassandra != null) { - CassandraOperationStatus result = cassandraDao.saveRecord(recordForCassandra); - if (!result.equals(CassandraOperationStatus.OK)) { - log.warn("Failed to persist to cassandra auditing event: {}", addRecordStatus.name()); - } - } - - } catch (Exception e) { - // Error during auditing shouldn't terminate flow - log.warn("Error during auditEvent: {}", e); - } - } - - private void formatUser(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) { - String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID); - - String user = AuditingLogFormatUtil.getUser(userDetails); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user); - } - } - - private void formatModifier(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier); - auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME); - } - - private void normalizeEmptyAuditStringValues(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - for (Entry<AuditingFieldsKeysEnum, Object> auditingEntry : auditingFields.entrySet()) { - if (auditingEntry.getKey().getValueClass().equals(String.class)) { - String auditingValue = (String) auditingEntry.getValue(); - boolean isEmpty = false; - if (auditingValue != null) { - String trimmedValue = auditingValue.trim(); - if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) { - isEmpty = true; - } - } else {// is null - isEmpty = true; - } - // Normalizing to "" - if (isEmpty) { - auditingEntry.setValue(Constants.EMPTY_STRING); - } - } - } - } +import java.util.Map; +import java.util.Map.Entry; + +@Component +public class AuditingManager { + + private static final Logger log = LoggerFactory.getLogger(AuditingManager.class); + private final AuditingDao auditingDao; + private final AuditCassandraDao cassandraDao; + + public AuditingManager(AuditingDao auditingDao, AuditCassandraDao cassandraDao) { + this.auditingDao = auditingDao; + this.cassandraDao = cassandraDao; + } + + // TODO remove after completing refactoring + public String auditEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) { + String msg = ""; + try { + boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit(); + if (disableAudit) { + return null; + } + // Adding UUID from thread local + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid()); + + Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status)); + + // normalizing empty string values - US471661 + normalizeEmptyAuditStringValues(auditingFields); + + // Format modifier + formatModifier(auditingFields); + + // Format user + formatUser(auditingFields); + + // Logging the event + msg = AuditingLogFormatUtil.logAuditEvent(auditingFields); + + // Determining the type of the auditing data object + AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); + log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType()); + ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType()); + if (!addRecordStatus.equals(ActionStatus.OK)) { + log.warn("Failed to persist auditing event: {}", addRecordStatus); + } + + AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields); + if (recordForCassandra != null) { + saveEventToCassandra(recordForCassandra); + } + + } catch (Exception e) { + // Error during auditing shouldn't terminate flow + log.warn("Error during auditEvent: {}", e); + } + return msg; + } + + + public String auditEvent(AuditEventFactory factory) { + if (ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit()) { + return null; + } + AuditingGenericEvent event = factory.getDbEvent(); + // Logging the event + //TODO - change this call after EELF Audit stuff merge + String msg = factory.getLogMessage(); + AuditingLogFormatUtil.logAuditEvent(msg); + + //TODO - remove this method after we got rid of ES + saveEventToElasticSearch(factory, event); + saveEventToCassandra(event); + return msg; + } + + private void saveEventToCassandra(AuditingGenericEvent event) { + CassandraOperationStatus result = cassandraDao.saveRecord(event); + if (!result.equals(CassandraOperationStatus.OK)) { + log.warn("Failed to persist to cassandra auditing event: {}", result.name()); + } + } + + private void saveEventToElasticSearch(AuditEventFactory factory, AuditingGenericEvent event) { + ActionStatus addRecordStatus = auditingDao.addRecord(event, factory.getAuditingEsType()); + if (!addRecordStatus.equals(ActionStatus.OK)) { + log.warn("Failed to persist auditing event: {}", addRecordStatus.name()); + } + } + + + private void formatUser(Map<AuditingFieldsKeysEnum, Object> auditingFields) { + if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) { + String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID); + + String user = AuditingLogFormatUtil.getUser(userDetails); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user); + } + } + + private void formatModifier(Map<AuditingFieldsKeysEnum, Object> auditingFields) { + String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier); + auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME); + } + + private void normalizeEmptyAuditStringValues(Map<AuditingFieldsKeysEnum, Object> auditingFields) { + for (Entry<AuditingFieldsKeysEnum, Object> auditingEntry : auditingFields.entrySet()) { + if (auditingEntry.getKey().getValueClass().equals(String.class)) { + String auditingValue = (String) auditingEntry.getValue(); + boolean isEmpty = false; + if (auditingValue != null) { + String trimmedValue = auditingValue.trim(); + if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) { + isEmpty = true; + } + } else {// is null + isEmpty = true; + } + // Normalizing to "" + if (isEmpty) { + auditingEntry.setValue(Constants.EMPTY_STRING); + } + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java new file mode 100644 index 0000000000..84c3a0392d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddCategoryEventFactory(CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java new file mode 100644 index 0000000000..6ee7624ddf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddGroupingCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddGroupingCategoryEventFactory(CommonAuditData commonFields, User modifier, String categoryName, + String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_GROUPING, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java new file mode 100644 index 0000000000..241d0c0fc5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddSubCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddSubCategoryEventFactory(CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_SUB_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java new file mode 100644 index 0000000000..9a2d7b09a8 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditCategoryEventFactory extends AuditBaseEventFactory { + + private final CategoryEvent event; + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\"" + + " GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(), + event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(action); + event = new CategoryEvent(getAction().getName(), commonFields, buildUserName(modifier), categoryName, + subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java new file mode 100644 index 0000000000..8c4de3c43d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetCategoryHierarchyEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory { + + private final GetCategoryHierarchyEvent event; + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditGetCategoryHierarchyEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, String details) { + super(action); + event = new GetCategoryHierarchyEvent(getAction().getName(), commonFields, buildUserName(modifier), details); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..907d73546f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory { + + public AuditAddKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..5ad7380051 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditAddRemoveKeyDistribEngineEventFactory extends AuditDistribEngineEventFactory{ + + private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " + + "API_KEY = \"%s\" STATUS = \"%s\""; + + public AuditAddRemoveKeyDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic()); + return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName, + event.getRole(), event.getApiKey(), event.getStatus()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java new file mode 100644 index 0000000000..7825cca0e9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditCreateTopicDistribEngineEventFactory extends AuditDistribEngineEventFactory{ + + private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" STATUS = \"%s\""; + + public AuditCreateTopicDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic()); + return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName, event.getStatus()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java new file mode 100644 index 0000000000..cb86f5059c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditDistribDeployEventFactory extends AuditBaseEventFactory { + + private DistributionDeployEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " + + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getCurrVersion(), event.getModifier(), event.getDid(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribDeployEventFactory(CommonAuditData commonFields, String currentVersion, + String did, User modifier, String resourceName, String resourceType) { + + super(AuditingActionEnum.DISTRIBUTION_DEPLOY); + this.event = new DistributionDeployEvent(getAction().getName(), commonFields, did, buildUserName(modifier), + currentVersion, resourceName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java new file mode 100644 index 0000000000..e8453b1d0b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; + +public class AuditDistribDownloadEventFactory extends AuditBaseEventFactory { + + private DistributionDownloadEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDistribDownloadEventFactory(CommonAuditData commonFields, DistributionData distributionData) { + + super(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD); + this.event = new DistributionDownloadEvent(getAction().getName(), commonFields, distributionData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceUrl(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java new file mode 100644 index 0000000000..3ebacb49d9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditDistribEngineEventFactory extends AuditBaseEventFactory{ + + protected final DistributionEngineEvent event; + + public AuditDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(action); + event = new DistributionEngineEvent(getAction().getName(), commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java new file mode 100644 index 0000000000..80c4590b8d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java @@ -0,0 +1,39 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; + +public class AuditDistribNotificationEventFactory extends AuditBaseEventFactory { + + private DistributionNotificationEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " + + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\" DID = \"%s\" " + + "TOPIC_NAME = \"%s\" STATUS = \"%s\" DESC = \"%s\" TENANT = \"%s\" VNF_WORKLOAD_CONTEXT = \"%s\" ENV_ID = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getCurrVersion(), event.getModifier(), event.getCurrState(), event.getDid(), event.getTopicName(), event.getStatus(), event.getDesc(), + event.getTenant(), event.getVnfWorkloadContext(), event.getEnvId()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribNotificationEventFactory(CommonAuditData commonFields, String currentState, String currentVersion, + String did, User modifier, String resourceName, + String resourceType, String topicName, OperationalEnvAuditData opEnvFields) { + + super(AuditingActionEnum.DISTRIBUTION_NOTIFY); + this.event = new DistributionNotificationEvent(getAction().getName(), commonFields, did, AuditBaseEventFactory.buildUserName(modifier), + currentState, currentVersion,resourceName, resourceType, topicName, opEnvFields); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java new file mode 100644 index 0000000000..3d71a200a3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditDistribStatusEventFactory extends AuditBaseEventFactory { + + private DistributionStatusEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" DID = \"%s\" CONSUMER_ID = \"%s\" " + + "TOPIC_NAME = \"%s\" RESOURCE_URL = \"%s\" STATUS_TIME = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), event.getResoureURL(), + event.getStatusTime(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribStatusEventFactory(CommonAuditData commonFields, String did, String consumerId, String topicName, + String resourceURL, String statusTime) { + + super(AuditingActionEnum.DISTRIBUTION_STATUS); + this.event = new DistributionStatusEvent(getAction().getName(), commonFields, did, consumerId, topicName, resourceURL, statusTime); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java new file mode 100644 index 0000000000..79d524a0dc --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory { + + private AuditingGetUebClusterEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" STATUS = \"%s\" STATUS_DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditGetUebClusterEventFactory(CommonAuditData commonFields, String consumerId) { + + super(AuditingActionEnum.GET_UEB_CLUSTER); + this.event = new AuditingGetUebClusterEvent(getAction().getName(), commonFields, consumerId); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java new file mode 100644 index 0000000000..2dbcde7b2c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditRegUnregDistribEngineEventFactory extends AuditDistribEngineEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" API_KEY = \"%s\" D_ENV = \"%s\" STATUS = \"%s\"" + + " DESC = \"%s\" DNOTIF_TOPIC = \"%s\" DSTATUS_TOPIC = \"%s\""; + + public AuditRegUnregDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, + String distStatusTopic, String distNotifTopic, String apiKey, String envName, String role) { + super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getApiKey(), event.getEnvironmentName(), + event.getStatus(), event.getDesc(), event.getDnotifTopic(),event.getDstatusTopic()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java new file mode 100644 index 0000000000..e2ce0312f7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditRegisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory { + + public AuditRegisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.DISTRIBUTION_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..fe7f335c77 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditRemoveKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory { + + public AuditRemoveKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java new file mode 100644 index 0000000000..d402d38e25 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUnregisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory { + + public AuditUnregisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java new file mode 100644 index 0000000000..942dae0507 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java @@ -0,0 +1,26 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditActivateServiceExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; + + public AuditActivateServiceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ACTIVATE_SERVICE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getStatus(), event.getServiceInstanceId(), + event.getInvariantUuid(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java new file mode 100644 index 0000000000..5e6256368e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" RESOURCE_NAME = \"%s\" " + + "RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditAssetExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(), + event.getResourceType(), event.getServiceInstanceId(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java new file mode 100644 index 0000000000..1a41d7d5f8 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditAssetGetMetadataExternalApiEventFactory extends AuditAssetExternalApiEventFactory { + + public AuditAssetGetMetadataExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_ASSET_METADATA, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..13558881c5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditAssetListExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(), + event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java new file mode 100644 index 0000000000..060cbd395e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\"" + + " PREV_STATE = \"%s\" CURR_STATE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditChangeLifecycleExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(), + event.getCurrState(), event.getServiceInstanceId(), event.getInvariantUuid(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java new file mode 100644 index 0000000000..07bac13495 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; + + public AuditCreateResourceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(), + event.getCurrState(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getStatus(), + event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java new file mode 100644 index 0000000000..fd8be4cc47 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\"" + + " STATUS = \"%s\" DESC = \"%s\""; + + public AuditCrudExternalApiArtifactEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), + event.getArtifactData(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..c2827b1e5d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditDeleteArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditDeleteArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_DELETE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java new file mode 100644 index 0000000000..134dfd2921 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDownloadArtifactExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getConsumerId(), event.getResourceURL(),event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java new file mode 100644 index 0000000000..4e233dee27 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditExternalApiEventFactory extends AuditBaseEventFactory { + + protected final ExternalApiEvent event; + + public AuditExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action); + event = new ExternalApiEvent(getAction().getName(), commonFields, resourceType, resourceName, consumerId, resourceUrl, + prevParams, currParams, AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData) ; + } + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..e97614551f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory { + + public AuditGetAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_ASSET_LIST, commonFields, resourceType, resourceName, + consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..379124dc4a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetFilteredAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory { + + public AuditGetFilteredAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_FILTERED_ASSET_LIST, commonFields, resourceType, resourceName, + consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java new file mode 100644 index 0000000000..168cd1b150 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetToscaModelExternalApiEventFactory extends AuditAssetExternalApiEventFactory { + + public AuditGetToscaModelExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_TOSCA_MODEL, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..5af8ff3d0d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditUpdateArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditUpdateArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_UPDATE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..02af363f46 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditUploadArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditUploadArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java new file mode 100644 index 0000000000..9bda0d22d6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + + public AuditArtifactResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + //TODO: check wheather or not "CONSUMER_ID =...RESOURCE_URL = " should be filled out - the info id not in the event + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getPrevArtifactUUID()), buildValue(event.getCurrArtifactUUID()), + buildValue(event.getArtifactData()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java new file mode 100644 index 0000000000..f5302957e1 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditCertificationResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " COMMENT = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getComment()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java new file mode 100644 index 0000000000..db76b78106 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditCreateUpdateResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " STATUS = \"%s\" DESC = \"%s\""; + + + public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java new file mode 100644 index 0000000000..62f95de6bd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" + + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDistStateChangeRequestResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()), + buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()), + buildValue(event.getDid()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java new file mode 100644 index 0000000000..3fd41b9681 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditDistStateChangeResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" + + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" STATUS = \"%s\" DESC = \"%s\" COMMENT = \"%s\""; + + + public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()), + buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()), + buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getComment())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java new file mode 100644 index 0000000000..64da0fd6db --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResourceAdminEventFactory { + + + private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"" ; + + + public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + } + + public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, + String invariantUuid, User modifier, String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, null, null, null, toscaNodeType); + } + + @Override public String getLogMessage() { + return String.format(LOG_STR_TOSCA, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getToscaNodeType())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java new file mode 100644 index 0000000000..2a188d2c1a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditResourceAdminEventFactory extends AuditBaseEventFactory { + + protected final ResourceAdminEvent event; + + public AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(action); + + this.event = new ResourceAdminEvent(action.getName(), commonFields, prevParams, currParams, resourceType, + resourceName, invariantUuid, AuditBaseEventFactory.buildUserName(modifier), + artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java new file mode 100644 index 0000000000..c7ea8cc428 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetUsersListEventFactory extends AuditBaseEventFactory { + private final GetUsersListEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier, + String userDetails) { + super(AuditingActionEnum.GET_USERS_LIST); + event = new GetUsersListEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier), userDetails); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java new file mode 100644 index 0000000000..4f97ae12c9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUserAccessEventFactory extends AuditBaseEventFactory { + + protected final static String LOG_STR = "ACTION = \"%s\" USER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + private final UserAccessEvent event; + + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + + public AuditUserAccessEventFactory(CommonAuditData commonFields, User user) { + super(AuditingActionEnum.USER_ACCESS); + event = new UserAccessEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(user)); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java new file mode 100644 index 0000000000..9c19c49b2d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUserAdminEventFactory extends AuditBaseEventFactory { + + final private UserAdminEvent event; + + protected final static String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" USER_BEFORE = \"%s\" USER_AFTER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getModifier()), buildValue(event.getUserBefore()), + buildValue(event.getUserAfter()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, User userBefore, User userAfter) { + super(action); + event = new UserAdminEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier), + AuditBaseEventFactory.buildUserNameExtended(userBefore), + AuditBaseEventFactory.buildUserNameExtended(userAfter)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java deleted file mode 100644 index 824b70073e..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.clean; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.CleanComponentsConfiguration; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component("asdcComponentsCleaner") -public class AsdcComponentsCleanerTask implements Runnable { - - private static Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class.getName()); - - @javax.annotation.Resource - private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null; - - private List<NodeTypeEnum> componentsToClean; - private long cleaningIntervalInMinutes; - - private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build()); - ScheduledFuture<?> scheduledFuture = null; - - @PostConstruct - public void init() { - log.trace("Enter init method of AsdcComponentsCleaner"); - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration(); - - if (cleanComponentsConfiguration == null) { - log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration"); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, "AsdcComponentsCleanerTask.init()", "AsdcComponentsCleanerTask.init()"); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", "fecth configuration"); - return; - - } - componentsToClean = new ArrayList<NodeTypeEnum>(); - List<String> components = cleanComponentsConfiguration.getComponentsToClean(); - if (components == null) { - log.info("no component were configured for cleaning"); - } - for (String component : components) { - NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component); - if (typeEnum != null) - componentsToClean.add(typeEnum); - } - - long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes(); - - if (intervalInMinutes < 1) { - log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default"); - intervalInMinutes = 60; - } - cleaningIntervalInMinutes = intervalInMinutes; - - startTask(); - - log.trace("End init method of AsdcComponentsCleaner"); - } - - @PreDestroy - public void destroy() { - this.stopTask(); - shutdownExecutor(); - } - - public void startTask() { - - log.debug("start task for cleaning components"); - - try { - - if (scheduledService != null) { - log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes); - scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, TimeUnit.MINUTES); - - } - } catch (Exception e) { - log.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", e.getMessage()); - - } - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - log.debug("Stop cleaning task. result = {}", result); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, "try to stop the polling task"); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", "try to stop the polling task"); - } - scheduledFuture = null; - } - - } - - private void shutdownExecutor() { - if (scheduledService == null) - return; - - scheduledService.shutdown(); // Disable new tasks from being submitted - try { - // Wait a while for existing tasks to terminate - if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS)) { - scheduledService.shutdownNow(); // Cancel currently executing - // tasks - // Wait a while for tasks to respond to being cancelled - if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS)) - log.debug("Pool did not terminate"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - scheduledService.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } - - @Override - public void run() { - try { - componentsCleanBusinessLogic.cleanComponents(componentsToClean); - } catch (Exception e) { - log.error("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", e.getMessage()); - } - - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java deleted file mode 100644 index b12b55ba8b..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.clean; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; -import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; -import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import fj.data.Either; - -@Component("componentsCleanBusinessLogic") -public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { - - @Autowired - private ResourceBusinessLogic resourceBusinessLogic; - - @Autowired - private ServiceBusinessLogic serviceBusinessLogic; - - private static Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class.getName()); - - public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean) { - - Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents = new HashMap<NodeTypeEnum, Either<List<String>, ResponseFormat>>(); - - log.trace("start cleanComponents"); - for (NodeTypeEnum type : componentsToClean) { - switch (type) { - case Resource: - processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic); - break; - case Service: - processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic); - break; - default: - log.debug("{} component type does not have cleaning method defined", type); - break; - } - } - - log.trace("end cleanComponents"); - return cleanedComponents; - } - - private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) { - Either<List<String>, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents(); - if (deleteMarkedResources.isRight()) { - log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage()); - } else { - if (log.isDebugEnabled()) { - StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": "); - for (String id : deleteMarkedResources.left().value()) { - sb.append(id).append(", "); - } - log.debug(sb.toString()); - } - } - cleanedComponents.put(type, deleteMarkedResources); - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java new file mode 100644 index 0000000000..0ee2dabf08 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java @@ -0,0 +1,1681 @@ +package org.openecomp.sdc.be.components.csar; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import fj.data.Either; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.CsarValidationUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.info.ArtifactTemplateInfo; +import org.openecomp.sdc.be.info.MergedArtifactInfo; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.heat.HeatParameterType; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.tosca.CsarUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH; + + +@org.springframework.stereotype.Component("csarArtifactsAndGroupsBusinessLogic") +public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(CsarArtifactsAndGroupsBusinessLogic.class); + private final Gson gson = new Gson(); + private static final Pattern pattern = Pattern.compile("\\..(.*?)\\.."); + @Autowired + protected ArtifactsBusinessLogic artifactsBusinessLogic; + + public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts, + boolean shouldLock, boolean inTransaction) { + + log.debug("parseResourceArtifactsInfoFromFile start"); + return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()) + .left() + .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts,shouldLock, inTransaction)) + .right() + .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;}) + .left() + .bind( c -> getResourcetFromGraph(c)); + } + + + public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts, + boolean shouldLock, boolean inTransaction){ + + Resource updatedResource = resource; + + Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile( + updatedResource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); + if (parseResourceInfoFromYamlEither.isRight()) { + ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + List<GroupDefinition> groups = updatedResource.getGroups(); + Map<String, ArtifactDefinition> deplymentArtifact = updatedResource.getDeploymentArtifacts(); + if (deplymentArtifact == null || deplymentArtifact.isEmpty()) { + if(groups != null){ + List<GroupDefinition> listToDelete = groups.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList()); + groupBusinessLogic.deleteGroups(updatedResource, listToDelete); + } + return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(), + createdNewArtifacts, shouldLock, inTransaction); + } + + List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = deplymentArtifact.values().stream().collect(Collectors.toList()); + + int labelCounter = createdDeplymentArtifactsAfterDelete.size(); + + + ////////////////////////////////////// create set parsed + ////////////////////////////////////// artifacts/////////////////////////////////////////// + Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); + + + List<ArtifactTemplateInfo> artifactsWithoutGroups = null; + if (parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)) { + artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT); + parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); + } + Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values(); + + Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts, shouldLock, inTransaction, + createdDeplymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection); + if(parsedArtifactsPerGroupEither.isRight()){ + log.error("Failed to parse artifacts. Status is {} ", parsedArtifactsPerGroupEither.right().value()); + return Either.right(parsedArtifactsPerGroupEither.right().value()); + } + + Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = parsedArtifactsPerGroupEither.left().value(); + + // find master in group + Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup( + groups, deplymentArtifact); + + ///////////////////////////////// find artifacts to + ///////////////////////////////// delete//////////////////////////////////////////////////// + + + Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<>(); + Set<ArtifactDefinition> artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeplymentArtifactsAfterDelete); + + Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet(); + Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, + artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete); + + List<ArtifactDefinition> deletedArtifacts = new ArrayList<>();; + Either<Resource, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow( + updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts); + if (deletedArtifactsEither.isRight()) { + log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value()); + + return Either.right(deletedArtifactsEither.right().value()); + + } + updatedResource = deletedArtifactsEither.left().value(); + + // need to update resource if we updated artifacts + if (!deletedArtifacts.isEmpty()) { + for (ArtifactDefinition deletedArtifact : deletedArtifacts) { + ArtifactDefinition artToRemove = null; + for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) { + if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) { + artToRemove = artFromResource; + break; + } + } + if (artToRemove != null) { + createdDeplymentArtifactsAfterDelete.remove(artToRemove); + } + + } + } + + ////////////// dissociate, associate or create + ////////////// artifacts//////////////////////////// + Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, + updatedResource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, + createdDeplymentArtifactsAfterDelete, mergedgroup, deletedArtifacts); + groups = updatedResource.getGroups(); + if (assDissotiateEither.isRight()) { + log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value()); + + return Either.right(assDissotiateEither.right().value()); + + } + updatedResource = assDissotiateEither.left().value(); + deplymentArtifact = updatedResource.getDeploymentArtifacts(); + createdDeplymentArtifactsAfterDelete.clear(); + if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { + for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) { + createdDeplymentArtifactsAfterDelete.add(entry.getValue()); + } + } + + // update vfModule names + Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet(); + if (groups != null && !groups.isEmpty()) { + Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNamesOnGraph(groups, updatedResource, inTransaction); + if (validateUpdateVfGroupNamesRes.isRight()) { + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + List<GroupDefinition> heatGroups = null; + + heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + + for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) { + + if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) { + updatedGroupDef.getMembers().clear(); + } + Map<String, String> members = new HashMap<>(); + Set<String> artifactsGroup = new HashSet<>(); + artifactsGroup.addAll(updatedGroupDef.getArtifacts()); + associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, + artifactsGroup, members); + if (!members.isEmpty()) { + updatedGroupDef.setMembers(members); + + } + + } + + } + + //////////////// create new artifacts in update + //////////////// flow//////////////////////////// + List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<>(); + + for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) { + ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey(); + boolean isNewGroup = true; + for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact + .entrySet()) { + Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue(); + Set<ArtifactDefinition> group = groupArtifacts.keySet(); + for (ArtifactDefinition artifactInfo : group) { + if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) { + parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName()); + isNewGroup = false; + } + } + } + if (isNewGroup) { + newArtifactsGroup.add(parsedArtifactMaster); + } + + } + if (!newArtifactsGroup.isEmpty()) { + Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); + int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups); + Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic + .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter); + if (validateGroupNamesRes.isRight()) { + return Either.right(validateGroupNamesRes.right().value()); + } + Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, + newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, + shouldLock, inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + + // updatedGroup + if (!groupForAssociateWithMembers.isEmpty()) { + + List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e) + .collect(Collectors.toList()); + + Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic + .updateGroups(updatedResource, groupsId); + if (updateVersionEither.isRight()) { + log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); + + return Either.right(updateVersionEither.right().value()); + + } + } + if (artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()) { + for (ArtifactTemplateInfo t : artifactsWithoutGroups) { + List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>(); + arrtifacts.add(t); + Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, + arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + + } + + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + return Either.left(eitherGerResource.left().value()); + } + + private Set<ArtifactDefinition> findArtifactThatNotInGroupToDelete( + Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, + List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) { + Set<ArtifactDefinition> artifactsToDelete = new HashSet<>(); + for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) { + Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue(); + for (ArtifactTemplateInfo template : artifactsNames) { + if(template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())){ + Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny(); + if(op.isPresent()){ + if(!op.get().getArtifactType().equalsIgnoreCase(template.getType())){ + artifactsToDelete.add(op.get()); + } + + } + } + } + } + + return artifactsToDelete; + } + + + private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, + Map<String, List<ArtifactTemplateInfo>> artifactsMap, + List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) { + + Either<Resource, ResponseFormat> resStatus = Either.left(resource); + + Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values(); + + for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) { + if (groupTemplateList != null) { + resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, + createdArtifacts, 0, shouldLock, inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + + return resStatus; + + } + + + private Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo, Resource resource, + List<ArtifactDefinition> createdNewArtifacts, boolean shouldLock, boolean inTransaction, + List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, int labelCounter, + Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection) { + + Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<>(); + + for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + if (parsedGroupTemplate.getGroupName() != null) { + parsedGroupTemplate.setGroupName(""); + Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<>(); + parsedArtifactsNames.add(parsedGroupTemplate); + List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { + createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames); + } + parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames); + } else { + List<ArtifactTemplateInfo> arrtifacts = new ArrayList<>(); + arrtifacts.add(parsedGroupTemplate); + Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, + resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, + labelCounter, shouldLock, inTransaction); + if (resStatus.isRight()) { + return Either.right(resStatus.right().value()); + } + + } + } + + } + return Either.left(parsedGroup); + } + + @SuppressWarnings({ "unchecked", "static-access" }) + public Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile( + Resource resource, String artifactsMetaFile, String artifactFileName, User user) { + + try { + JsonObject jsonElement = new JsonObject(); + jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass()); + + JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE); + if (importStructureElement == null || importStructureElement.isJsonNull()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<>(); + artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class); + if (artifactTemplateMap.isEmpty()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + Set<String> artifactsTypeKeys = artifactTemplateMap.keySet(); + Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<>(); + List<ArtifactTemplateInfo> allGroups = new ArrayList<>(); + for (String artifactsTypeKey : artifactsTypeKeys) { + + Either <List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName, + artifactTemplateMap, allGroups, artifactsTypeKey); + if(artifactTemplateInfoListEither.isRight()){ + return Either.right(artifactTemplateInfoListEither.right().value()); + } + artifactsMap.put(artifactsTypeKey, artifactTemplateInfoListEither.left().value()); + } + int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups()); + Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic + .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter); + if (validateGroupNamesRes.isRight()) { + return Either.right(validateGroupNamesRes.right().value()); + } + return Either.left(artifactsMap); + } catch (Exception e) { + log.debug("Artifact file is not in expected format, fileName {}", artifactFileName); + log.debug("failed with exception.", e); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + } + + private Either< List<ArtifactTemplateInfo>, ResponseFormat> parseArtifactTemplateList(String artifactFileName, + Map<String, List<Map<String, Object>>> artifactTemplateMap, List<ArtifactTemplateInfo> allGroups, + String artifactsTypeKey) { + List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey); + Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule( + artifactsTypeKey, o); + if (artifactTemplateInfoListPairStatus.isRight()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(artifactTemplateInfoListPairStatus.right().value()); + } + List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value(); + if (artifactTemplateInfoList == null) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + + } + if (!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) { + allGroups.addAll(artifactTemplateInfoList); + } + return Either.left(artifactTemplateInfoList); + } + + private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, + List<Map<String, Object>> jsonObject) { + List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<>(); + for (Map<String, Object> o : jsonObject) { + Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo + .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, + null); + if (artifacttemplateInfoStatus.isRight()) { + return Either.right(artifacttemplateInfoStatus.right().value()); + } + + ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value(); + if (artifacttemplateInfo != null) { + artifactTemplateInfoList.add(artifacttemplateInfo); + } + + } + return Either.left(artifactTemplateInfoList); + } + + + + private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, + List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shouldLock, boolean inTransaction) { + Either<Resource, ResponseFormat> resStatus = Either.left(resource); + List<GroupDefinition> createdGroups = resource.getGroups(); + List<GroupDefinition> heatGroups = null; + if (createdGroups != null && !createdGroups.isEmpty()) { + + heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + + } + List<GroupDefinition> needToCreate = new ArrayList<>(); + for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { + String groupName = groupTemplateInfo.getGroupName(); + Set<String> artifactsGroup = new HashSet<>(); + Set<String> artifactsUUIDGroup = new HashSet<>(); + + log.debug("createDeploymentArtifactsFromCsar start"); + resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, + artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); + log.debug("createDeploymentArtifactsFromCsar end"); + if (resStatus.isRight()) { + return resStatus; + } + if (groupName != null && !groupName.isEmpty()) { + + Either<GroupDefinition, ResponseFormat> groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo, + groupName, artifactsGroup, artifactsUUIDGroup); + if (groupDefinitionEither.isRight()) { + return Either.right(groupDefinitionEither.right().value()); + } + needToCreate.add(groupDefinitionEither.left().value()); + } + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + + componentParametersView.setIgnoreComponentInstances(false); + + Either<Resource, StorageOperationStatus> component = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), componentParametersView); + + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic + .addGroups(component.left().value(), needToCreate); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + + return Either.left(component.left().value()); + } + + private Either<GroupDefinition, ResponseFormat> buildGroupDefinition(List<ArtifactDefinition> createdArtifacts, + List<GroupDefinition> heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName, + Set<String> artifactsGroup, Set<String> artifactsUUIDGroup) { + + Map<String, String> members = new HashMap<>(); + + associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); + + List<String> artifactsList = new ArrayList<>(artifactsGroup); + List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup); + + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setName(groupName); + groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); + groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + + if (!members.isEmpty()) { + groupDefinition.setMembers(members); + } + List<GroupProperty> properties = new ArrayList<>(); + GroupProperty prop = new GroupProperty(); + prop.setName(Constants.IS_BASE); + prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); + properties.add(prop); + Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, + createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); + log.debug("createGroup start"); + return Either.left(groupDefinition); + } + + private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, + Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, + boolean shoudLock, boolean inTransaction) { + Either<Resource, ResponseFormat> resStatus = Either.left(resource); + + String artifactUid = ""; + String artifactEnvUid = ""; + String artifactUUID = ""; + + + // check if artifacts already exist + Either<ArtifactDefinition, ResponseFormat> createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts); + if(createdArtifactEther.isRight()){ + return Either.right(createdArtifactEther.right().value()); + } + ArtifactDefinition createdArtifact = createdArtifactEther.left().value(); + if(createdArtifact == null){ + + Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, + artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction); + if (newArtifactEither.isRight()) { + resStatus = Either.right(newArtifactEither.right().value()); + return resStatus; + } + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } + }else{ + artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); + } + artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } + + List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null) { + for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { + resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, + artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + return resStatus; + } + + private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { + String artifactEnvUid = ""; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX; + } + return artifactEnvUid; + } + + private Either<ArtifactDefinition, ResponseFormat> checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts){ + + ArtifactDefinition res = null; + String artifactFileName = artifactTemplateInfo.getFileName(); + Optional<ArtifactDefinition> op = createdArtifacts.stream().filter(a -> a.getArtifactName().equals(artifactFileName)).findAny(); + if(op.isPresent()){ + res = op.get(); + if (!res.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), res.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), res.getArtifactType())); + } + } + return Either.left(res); + + + } + + private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, + String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, + int label, boolean inTransaction) { + int updatedlabel = label; + final String artifactFileName = artifactTemplateInfo.getFileName(); + Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, + artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) { + return Either.right(artifactContententStatus.right().value()); + } + updatedlabel += createdArtifacts.size(); + + Map<String, Object> json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo, + artifactContententStatus.left().value().getValue(), updatedlabel); + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), json, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE)); + + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + if (currentInfo.getHeatParameters() != null) { + + Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, + artifactTemplateInfo, currentInfo, false); + if (updateEnvEither.isRight()) { + log.debug("failed to update parameters to artifact {}", artifactFileName); + return Either.right(updateEnvEither.right().value()); + + } + currentInfo = updateEnvEither.left().value(); + + } + + createdArtifacts.add(currentInfo); + + return Either.left(currentInfo); + + } + + + + private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, + ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { + + Resource updatedResource = resource; + Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo); + if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { + + Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), + CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), + componentsUtils); + if (artifactparamsStatus.isRight()) { + resStatus = Either.right(artifactparamsStatus.right().value()); + return resStatus; + } + Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters( + ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), + artifactparamsStatus.left().value().getValue(), false); + + if (propsStatus.isLeft()) { + List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value(); + resStatus = updateHeatParams(updatedResource, currentInfo, updatedHeatEnvParams); + if (resStatus.isRight()) { + return resStatus; + } + + } + } + if (isUpdateEnv) { + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreArtifacts(false); + parametersView.setIgnoreGroups(false); + + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + resStatus = Either.right(responseFormat); + return resStatus; + + } + + updatedResource = eitherGerResource.left().value(); + Map<String, ArtifactDefinition> artifacts = updatedResource.getDeploymentArtifacts(); + Optional<ArtifactDefinition> op = artifacts.values().stream().filter( + p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())) + .findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation + .updateArifactOnResource(artifactInfoHeatEnv, updatedResource.getUniqueId(), + artifactInfoHeatEnv.getUniqueId(), null, null); + if (updateArifactOnResource.isRight()) { + log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", + updatedResource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), + artifactInfoHeatEnv.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); + } + resStatus = Either.left(updateArifactOnResource.left().value()); + } + } + return resStatus; + } + + private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, + String fileName, byte[] content, boolean is64Encoded) { + // extract heat parameters + String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content); + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils + .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType); + if (heatParameters.isRight()) { + log.debug("File {} is not in expected key-value form in csar ", fileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", + ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName)); + + } + return Either.left(heatParameters.left().value()); + + } + + private Either<ArtifactDefinition, ResponseFormat> updateHeatParams(Resource resource, + ArtifactDefinition currentInfo, List<HeatParameterDefinition> updatedHeatEnvParams) { + + Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo); + List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null + && !currentHeatEnvParams.isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) { + updatedParamValue = heatEnvParam.getDefaultValue(); + } + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, + ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); + resStatus = Either.right(responseFormat); + return resStatus; + } + currHeatParam.setCurrentValue( + paramType.getConverter().convert(updatedParamValue, null, null)); + + break; + } + } + } + currentInfo.setListHeatParameters(currentHeatEnvParams); + Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation + .updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), + null, null); + if (updateArifactOnResource.isRight()) { + log.debug( + "Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", + resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); + } + resStatus = Either.left(updateArifactOnResource.left().value()); + } + return resStatus; + } + + + + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson( + Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation) { + + String jsonStr = gson.toJson(json); + + String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr); + ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, + ArtifactDefinition.class); + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic + .validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, + artifactUniqueId, artifactDefinitionFromJson, origMd5, jsonStr, null, null, user, + resource, false, true, false); + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + return Either.left(uploadArtifactToService.left().value()); + } + + private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, + List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, + Set<String> artifactsGroup, Map<String, String> members) { + if (heatGroups != null && !heatGroups.isEmpty()) { + for (GroupDefinition heatGroup : heatGroups) { + List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties(); + if (grpoupProps != null) { + associatemembersToVFgroups(createdArtifacts, artifactsFromResource, grpoupProps, artifactsGroup, heatGroup, members); + } + } + + } + } + + private void associatemembersToVFgroups(List<ArtifactDefinition> createdArtifacts,List<ArtifactDefinition> artifactsFromResource, List<GroupProperty> grpoupProps, Set<String> artifactsGroup, GroupDefinition heatGroup, Map<String, String> members){ + Optional<GroupProperty> op = grpoupProps.stream() + .filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny(); + if (op.isPresent()) { + GroupProperty prop = op.get(); + String heatFileNAme = prop.getValue(); + if (null == heatFileNAme || heatFileNAme.isEmpty()) { + return; + } + List<ArtifactDefinition> artifacts = new ArrayList<>(); + for (String artifactId : artifactsGroup) { + Optional<ArtifactDefinition> opArt = createdArtifacts.stream() + .filter(p -> p.getUniqueId().equals(artifactId)).findAny(); + if (opArt.isPresent()) { + artifacts.add(opArt.get()); + } + if (artifactsFromResource != null) { + opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)) + .findAny(); + if (opArt.isPresent()) { + artifacts.add(opArt.get()); + } + } + } + Optional<ArtifactDefinition> resOp = artifacts.stream() + .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); + if (resOp.isPresent()) { + members.putAll(heatGroup.getMembers()); + } + } + } + + public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, + List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, + GroupTypeDefinition groupType) { + Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager() + .getConfiguration().getVfModuleProperties(); + vfModuleProperties.entrySet().forEach(p -> { + GroupProperty prop = new GroupProperty(); + prop.setName(p.getKey()); + if (isBase) { + prop.setValue(p.getValue().getForBaseModule()); + prop.setDefaultValue(p.getValue().getForBaseModule()); + } else { + prop.setValue(p.getValue().getForNonBaseModule()); + prop.setDefaultValue(p.getValue().getForNonBaseModule()); + } + properties.add(prop); + + }); + GroupProperty proplabel = new GroupProperty(); + proplabel.setName("vf_module_label"); + + Matcher matcher = pattern.matcher(moduleName); + + if (matcher.find()) { + proplabel.setValue(matcher.group(1)); + proplabel.setDefaultValue(matcher.group(1)); + } else { + proplabel.setValue(moduleName); + proplabel.setDefaultValue(moduleName); + } + properties.add(proplabel); + + GroupProperty propvolume = new GroupProperty(); + propvolume.setName("volume_group"); + boolean isVolume = false; + for (String artifactId : artifactsInGroup) { + ArtifactDefinition artifactDef = null; + artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId); + if (artifactDef != null + && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + isVolume = true; + break; + } + } + propvolume.setValue(String.valueOf(isVolume)); + propvolume.setDefaultValue(String.valueOf(isVolume)); + properties.add(propvolume); + mergeWithGroupTypeProperties(properties, groupType.getProperties()); + return properties; + } + + private void mergeWithGroupTypeProperties(List<GroupProperty> properties, + List<PropertyDefinition> groupTypeProperties) { + + Map<String, GroupProperty> propertiesMap = properties.stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p)); + for (PropertyDefinition groupTypeProperty : groupTypeProperties) { + if (!propertiesMap.containsKey(groupTypeProperty.getName())) { + properties.add(new GroupProperty(groupTypeProperty)); + } + } + } + + private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow( + Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, + Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, + Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, + List<ArtifactDefinition> createdDeplymentArtifacts) { + Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<>(); + for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact + .entrySet()) { + Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue(); + boolean isNeedToDeleteGroup = true; + List<ArtifactDefinition> listToDelete = null; + for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { + listToDelete = createdArtifactMap.get(maserArtifact); + for (ArtifactDefinition artToDelete : listToDelete) { + findArtifactToDelete(parsedGroup, artifactsToDelete, artToDelete, createdDeplymentArtifacts); + } + if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) { + GroupDefinition group = groupListEntry.getKey(); + for (ArtifactDefinition artifactDefinition : artifactsToDelete) { + if (CollectionUtils.isNotEmpty(group.getArtifacts()) + && group.getArtifacts().contains(artifactDefinition.getUniqueId())) { + group.getArtifacts().remove(artifactDefinition.getUniqueId()); + + } + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) + && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) { + group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID()); + + } + } + + } + + for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { + if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) { + MergedArtifactInfo mergedGroup = new MergedArtifactInfo(); + mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact); + mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact)); + mergedgroup.put(groupListEntry.getKey(), mergedGroup); + isNeedToDeleteGroup = false; + + } + } + + } + if (isNeedToDeleteGroup) { + groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete); + } + + } + return mergedgroup; + } + + private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, + Set<ArtifactDefinition> artifactsToDelete, ArtifactDefinition artifact, + List<ArtifactDefinition> createdDeplymentArtifacts) { + boolean isNeedToDeleteArtifact = true; + String artifactType = artifact.getArtifactType(); + ArtifactDefinition generatedFromArt = null; + if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { + Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream() + .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + generatedFromArt = op.get(); + } + + } + + for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) { + Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue(); + for (ArtifactTemplateInfo template : artifactsNames) { + if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) + && artifactType.equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; + + } else { + + if (generatedFromArt != null) { + if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) + && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; + } + } + } + } + + } + if (isNeedToDeleteArtifact) { + artifactsToDelete.add(artifact); + + } + } + + private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup( + List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) { + Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<>(); + + for (GroupDefinition group : groups) { + Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<>(); + List<ArtifactDefinition> artifacts = new ArrayList<>(); + List<String> artifactsList = group.getArtifacts(); + if (artifactsList != null && !artifactsList.isEmpty()) { + + ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, + artifactsList); + if (masterArtifact != null) { + gupsMap.put(masterArtifact, artifacts); + } + groupArtifact.put(group, gupsMap); + + } + } + return groupArtifact; + } + + private Either<Resource, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, + User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete, + Map<String, List<ArtifactDefinition>> groupToDelete, List<ArtifactDefinition> deletedArtifacts) { + + Resource updatedResource = resource; + + String resourceId = updatedResource.getUniqueId(); + if (!artifactsToDelete.isEmpty()) { + for (ArtifactDefinition artifact : artifactsToDelete) { + String artifactType = artifact.getArtifactType(); + ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); + if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic + .handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, + ComponentTypeEnum.RESOURCE, updatedResource, shouldLock, inTransaction); + if (handleDelete.isRight()) { + return Either.right(handleDelete.right().value()); + } + + deletedArtifacts.add(handleDelete.left().value().left().value()); + } + + } + } + if (!groupToDelete.isEmpty()) { + log.debug("try to delete group"); + List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>(); + List<GroupDefinition> groups = updatedResource.getGroups(); + for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) { + Optional<GroupDefinition> op = groups.stream() + .filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny(); + if (op.isPresent()) { + groupDefinitionstoDelete.add(op.get()); + } + + } + if (!groupDefinitionstoDelete.isEmpty()) { + Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, groupDefinitionstoDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + } + List<GroupDefinition> oldGroups = updatedResource.getGroups(); + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + updatedResource = eitherGerResource.left().value(); + updatedResource.setGroups(oldGroups); + return Either.left(updatedResource); + } + + private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, + Set<ArtifactTemplateInfo> parsedArtifactsName) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + parsedArtifactsName.add(parsedGroupTemplate); + List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); + } + } + } + + private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, + List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, + int labelCounter, boolean shouldLock, boolean inTransaction) { + + Resource updatedResource = resource; + + Either<Resource, ResponseFormat> resStatus = Either.left(updatedResource); + List<GroupDefinition> createdGroups = updatedResource.getGroups(); + List<GroupDefinition> heatGroups = null; + if (createdGroups != null && !createdGroups.isEmpty()) { + heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + } + + List<GroupDefinition> needToAdd = new ArrayList<>(); + for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { + String groupName = groupTemplateInfo.getGroupName(); + Set<String> artifactsGroup = new HashSet<>(); + Set<String> artifactsUUIDGroup = new HashSet<>(); + + resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup, + groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + if (groupName != null && !groupName.isEmpty()) { + Map<String, String> members = new HashMap<>(); + associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, + members); + + List<String> artifactsList = new ArrayList<>(artifactsGroup); + List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup); + + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setName(groupName); + groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); + groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + + if (!members.isEmpty()) { + groupDefinition.setMembers(members); + } + + List<GroupProperty> properties = new ArrayList<>(); + GroupProperty prop = new GroupProperty(); + prop.setName(Constants.IS_BASE); + prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); + properties.add(prop); + + List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); + createdArtifacts.addAll(createdNewArtifacts); + createdArtifacts.addAll(artifactsFromResource); + Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, + createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); + + needToAdd.add(groupDefinition); + } + } + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreComponentInstances(false); + + Either<Resource, StorageOperationStatus> component = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId(), componentParametersView); + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + updatedResource = component.left().value(); + + Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd); + if (addGroups.isRight()) { + return Either.right(addGroups.right().value()); + } + + return resStatus; + } + + private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo, + List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, + boolean shoudLock, boolean inTransaction) { + Either<Resource, ResponseFormat> resStatus = Either.left(resource); + String artifactFileName = artifactTemplateInfo.getFileName(); + String artifactUid = ""; + String artifactUUID = ""; + String artifactEnvUid = ""; + boolean alreadyExist = false; + + // check if artifacts already exist + if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) { + for (ArtifactDefinition artifactFromResource : artifactsFromResource) { + if (artifactFromResource.getArtifactName().equals(artifactFileName)) { + artifactUid = artifactFromResource.getUniqueId(); + artifactUUID = artifactFromResource.getArtifactUUID(); + if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), artifactFromResource.getArtifactType())); + } + alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource); + break; + } + + } + + } + if (!alreadyExist) { + for (ArtifactDefinition createdArtifact : createdArtifacts) { + if (createdArtifact.getArtifactName().equals(artifactFileName)) { + artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); + + if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); + } + alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); + break; + } + + } + } + // if not exist need to create + if (!alreadyExist) { + + Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, + ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction); + if (newArtifactEither.isRight()) { + resStatus = Either.right(newArtifactEither.right().value()); + return resStatus; + } + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } + } + + artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } + + List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null) { + for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { + resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, + relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + return resStatus; + } + + private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, + Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock, + boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, + Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) { + Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<>(); + Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<>(); + Either<Resource, ResponseFormat> resEither = Either.left(resource); + for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) { + List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue() + .getListToDissotiateArtifactFromGroup(deletedArtifacts); + GroupDefinition grDef = entry.getKey(); + if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) { + for (ArtifactDefinition art : dissArtifactsInGroup) { + grDef.getArtifacts().remove(art.getUniqueId()); + grDef.getArtifactsUuid().remove(art.getArtifactUUID()); + } + } + + List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup(); + if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) { + artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup); + } + + List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue() + .getListToUpdateArtifactInGroup(); + if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) { + artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate); + } + } + + if (!artifactsToUpdateMap.isEmpty()) { + List<ArtifactDefinition> updatedArtifacts = new ArrayList<>(); + for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap + .entrySet()) { + List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry + .getValue(); + GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey(); + + for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) { + String prevUUID = artifact.getKey().getArtifactUUID(); + String prevId = artifact.getKey().getUniqueId(); + String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey()); + Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar( + csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts, + artifact.getRight().getRelatedArtifactsInfo()); + if (updateArtifactEither.isRight()) { + log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value()); + resEither = Either.right(updateArtifactEither.right().value()); + return resEither; + } + ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value(); + if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) + || !prevId.equals(artAfterUpdate.getUniqueId())) { + groupToUpdate.getArtifacts().remove(prevId); + groupToUpdate.getArtifactsUuid().remove(prevUUID); + groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId()); + groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); + } + Optional<ArtifactDefinition> op = updatedArtifacts.stream() + .filter(p -> p.getGeneratedFromId() != null + && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())) + .findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + groupToUpdate.getArtifacts().remove(prevHeatEnvId); + groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId()); + } + + } + } + } + + for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) { + List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue(); + Set<String> arifactsUids = new HashSet<>(); + Set<String> arifactsUuids = new HashSet<>(); + for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try + // to + // find + // artifact + // in + // resource + boolean isCreate = true; + for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) { + if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) { + arifactsUids.add(createdArtifact.getUniqueId()); + arifactsUuids.add(createdArtifact.getArtifactUUID()); + isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream() + .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); + if (op.isPresent()) { + this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), + resource.getComponentType().getNodeType()); + + } + } + + break; + } + + } + if (isCreate) { // check if already created + for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) { + if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) { + arifactsUids.add(createdNewArtifact.getUniqueId()); + arifactsUuids.add(createdNewArtifact.getArtifactUUID()); + isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + } + break; + } + } + } + + if (isCreate) { + Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, + resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, inTransaction); + if (createArtifactEither.isRight()) { + resEither = Either.right(createArtifactEither.right().value()); + return resEither; + } + ArtifactDefinition createdArtifact = createArtifactEither.left().value(); + arifactsUids.add(createdArtifact.getUniqueId()); + arifactsUuids.add(createdArtifact.getArtifactUUID()); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId(); + arifactsUids.add(heatEnvId); + } + } + + } + if (arifactsUids != null && !arifactsUids.isEmpty()) { + List<String> artifactsToAssociate = new ArrayList<>(); + artifactsToAssociate.addAll(arifactsUids); + GroupDefinition assotiateGroup = associateEntry.getKey(); + assotiateGroup.getArtifacts().addAll(arifactsUids); + assotiateGroup.getArtifactsUuid().addAll(arifactsUuids); + } + } + + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreArtifacts(false); + parametersView.setIgnoreGroups(false); + + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + resEither = Either.right(responseFormat); + return resEither; + + } + resEither = Either.left(eitherGerResource.left().value()); + return resEither; + } + + private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo, + List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts) { + + Either<ArtifactDefinition, ResponseFormat> resStatus = null; + String artifactFileName = artifactTemplateInfo.getFileName(); + + // check if artifacts already exist + for (ArtifactDefinition updatedArtifact : updatedArtifacts) { + if (updatedArtifact.getArtifactName().equals(artifactFileName)) { + if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, + artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + resStatus = Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), updatedArtifact.getArtifactType())); + return resStatus; + } + resStatus = Either.left(updatedArtifact); + return resStatus; + } + + } + + Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), + CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) { + resStatus = Either.right(artifactContententStatus.right().value()); + return resStatus; + } + + Map<String, Object> json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, + oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), + oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(), + artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts, oldArtifact.getIsFromCsar()); + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), json, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE)); + + if (uploadArtifactToService.isRight()) { + resStatus = Either.right(uploadArtifactToService.right().value()); + return resStatus; + } + ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + updatedArtifacts.add(currentInfo); + + Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, + artifactTemplateInfo, currentInfo, true); + if (updateEnvEither.isRight()) { + log.debug("failed to update parameters to artifact {}", artifactFileName); + resStatus = Either.right(updateEnvEither.right().value()); + return resStatus; + } + + updatedArtifacts.add(updateEnvEither.left().value()); + resStatus = Either.left(currentInfo); + + return resStatus; + + } + + public Either<Resource, ResponseFormat> deleteVFModules(Resource resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) { + Resource updatedResource = resource; + List<GroupDefinition> groupsToDelete = updatedResource.getGroups(); + if(groupsToDelete != null && !groupsToDelete.isEmpty()){ + List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList()); + if(vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()){ + for(GroupDefinition gr : vfGroupsToDelete){ + List<String> artifacts = gr.getArtifacts(); + for (String artifactId : artifacts) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, + updatedResource, shouldLock, inTransaction); + if (handleDelete.isRight()) { + log.debug("Couldn't delete artifact {}", artifactId); + return Either.right(handleDelete.right().value()); + } + } + + } + groupBusinessLogic.deleteGroups(updatedResource, vfGroupsToDelete); + + Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId()); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + updatedResource = eitherGetResource.left().value(); + } + } + return Either.left(updatedResource); + } + + private Either<Resource, ResponseFormat> getResourcetFromGraph(Resource component){ + log.debug("getResource start"); + return toscaOperationFacade.getToscaElement(component.getUniqueId()) + .right() + .map(rf -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(rf), component)) + .left() + .map (c -> (Resource) c); + + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java new file mode 100644 index 0000000000..0519f435e3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.http.conn.ConnectTimeoutException; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.SupplierThrows; +import org.openecomp.sdc.common.http.client.api.HttpExecuteException; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.client.api.Responses; +import org.openecomp.sdc.common.http.config.ExternalServiceConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.util.Properties; +import java.util.UUID; + +@Component +public class AaiRequestHandler { + + private static final Logger logger = LoggerFactory.getLogger(AaiRequestHandler.class); + private ExternalServiceConfig aaiConfig; + + protected static final String OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM = "operationalEnvironments"; + protected static final String OPERATIONAL_ENV_RESOURCE = "/operational-environment"; + + @PostConstruct + public void init() { + logger.debug("AaiRequestHandler has been initialized."); + + aaiConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getAaiConfig(); + logger.debug("AaiRequestHandler Configuration={}", aaiConfig); + } + + + public HttpResponse<String> getOperationalEnvById(String id) { + Properties headers = createHeaders(); + String url = String.format("%s%s%s/%s", + aaiConfig.getHttpRequestConfig().getServerRootUrl(), + aaiConfig.getHttpRequestConfig().getResourceNamespaces().get(OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM), + OPERATIONAL_ENV_RESOURCE, id); + + SupplierThrows<HttpResponse<String>, Exception> httpGet = () -> HttpRequest.get(url, headers, aaiConfig.getHttpClientConfig()); + long maxRetries = aaiConfig.getHttpClientConfig().getNumOfRetries(); + try { + return FunctionalInterfaces.retryMethodOnException(httpGet, this::retryOnException, maxRetries); + } + catch (Exception e) { + logger.debug("Request failed with exception {}", getCause(e).getMessage()); + return Responses.INTERNAL_SERVER_ERROR; + } + } + + + private boolean retryOnException(Exception e) { + Throwable cause = getCause(e); + return !(cause instanceof ConnectTimeoutException || cause instanceof ConnectException || cause instanceof SocketTimeoutException); + } + + + private Throwable getCause(Exception e) { + if (e instanceof HttpExecuteException) { + return e.getCause(); + } + return e; + } + + + private Properties createHeaders() { + Properties headers = new Properties(); + headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.put(Constants.X_TRANSACTION_ID_HEADER, UUID.randomUUID().toString()); + + return headers; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java index e1a1270fe3..9c46c68cd8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java @@ -20,177 +20,185 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; - public class ArtifactInfoImpl implements IArtifactInfo { - private String artifactName; - private ArtifactTypeEnum artifactType; - private String artifactURL; - private String artifactChecksum; - private String artifactDescription; - private Integer artifactTimeout; - private String artifactUUID; - private String artifactVersion; - private String generatedFromUUID; - private List<String> relatedArtifacts; - - public ArtifactInfoImpl() { - } - - private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List<String> relatedArtifacts) { - artifactName = artifactDef.getArtifactName(); - artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType()); - artifactChecksum = artifactDef.getArtifactChecksum(); - artifactDescription = artifactDef.getDescription(); - artifactTimeout = artifactDef.getTimeout(); - artifactUUID = artifactDef.getArtifactUUID(); - artifactVersion = artifactDef.getArtifactVersion(); - this.relatedArtifacts = relatedArtifacts; - this.generatedFromUUID = generatedFromUUID; - } - - public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection<ArtifactDefinition> list) { - List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>(); - Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); - if (list != null) { - for (ArtifactDefinition artifactDef : list) { - String generatedFromUUID = null; - if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { - ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); - generatedFromUUID = artifactFrom.getArtifactUUID(); - } - ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts())); - String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName()); - artifactInfoImpl.setArtifactURL(artifactURL); - ret.add(artifactInfoImpl); - } - } - return ret; - - } - - public static List<ArtifactInfoImpl> convertServiceArtifactToArtifactInfoImpl(Service service, Collection<ArtifactDefinition> list) { - List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>(); - Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); - if (list != null) { - for (ArtifactDefinition artifactDef : list) { - String generatedFromUUID = null; - if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { - ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); - generatedFromUUID = artifactFrom.getArtifactUUID(); - } - ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts())); - String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName()); - artifactInfoImpl.setArtifactURL(artifactURL); - ret.add(artifactInfoImpl); - } - } - return ret; - - } - - private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map<String, ArtifactDefinition> artifacts) { - List<String> requiredArtifacts = null; - if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) { - requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList()); - } - return requiredArtifacts; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public void setArtifactType(ArtifactTypeEnum artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public void setArtifactChecksum(String artifactChecksum) { - this.artifactChecksum = artifactChecksum; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public Integer getArtifactTimeout() { - return artifactTimeout; - } - - public void setArtifactTimeout(Integer artifactTimeout) { - this.artifactTimeout = artifactTimeout; - } - - public List<String> getRelatedArtifacts() { - return relatedArtifacts; - } - - public void setRelatedArtifacts(List<String> relatedArtifacts) { - this.relatedArtifacts = relatedArtifacts; - } - - @Override - public String toString() { - return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" - + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]"; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getGeneratedFromUUID() { - return generatedFromUUID; - } - - public void setGeneratedFromUUID(String generatedFromUUID) { - this.generatedFromUUID = generatedFromUUID; - } + private String artifactName; + private ArtifactTypeEnum artifactType; + private String artifactURL; + private String artifactChecksum; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactUUID; + private String artifactVersion; + private String generatedFromUUID; + private List<String> relatedArtifacts; + + public ArtifactInfoImpl() { + } + + private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List<String> relatedArtifacts) { + artifactName = artifactDef.getArtifactName(); + artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType()); + artifactChecksum = artifactDef.getArtifactChecksum(); + artifactDescription = artifactDef.getDescription(); + artifactTimeout = artifactDef.getTimeout(); + artifactUUID = artifactDef.getArtifactUUID(); + artifactVersion = artifactDef.getArtifactVersion(); + this.relatedArtifacts = relatedArtifacts; + this.generatedFromUUID = generatedFromUUID; + } + + public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection<ArtifactDefinition> list) { + List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>(); + Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); + if (list != null) { + for (ArtifactDefinition artifactDef : list) { + String generatedFromUUID = null; + if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { + ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); + generatedFromUUID = artifactFrom.getArtifactUUID(); + } + ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts())); + String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName()); + artifactInfoImpl.setArtifactURL(artifactURL); + ret.add(artifactInfoImpl); + } + } + ret.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout); + return ret; + + } + + public static List<ArtifactInfoImpl> convertServiceArtifactToArtifactInfoImpl(Service service, Collection<ArtifactDefinition> list) { + List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>(); + Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); + if (list != null) { + for (ArtifactDefinition artifactDef : list) { + String generatedFromUUID = null; + if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { + ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); + generatedFromUUID = artifactFrom.getArtifactUUID(); + } + ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts())); + String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName()); + artifactInfoImpl.setArtifactURL(artifactURL); + ret.add(artifactInfoImpl); + } + } + return ret; + + } + + private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map<String, ArtifactDefinition> artifacts) { + List<String> requiredArtifacts = null; + if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) { + requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList()); + } + return requiredArtifacts; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public void setArtifactType(ArtifactTypeEnum artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public List<String> getRelatedArtifacts() { + return relatedArtifacts; + } + + public void setRelatedArtifacts(List<String> relatedArtifacts) { + this.relatedArtifacts = relatedArtifacts; + } + + @Override + public String toString() { + return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]"; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + public void updateArtifactTimeout(){ + int currentConfigTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getCurrentArtifactInstallationTimeout(); + if(artifactTimeout == null || artifactTimeout < currentConfigTimeout) + artifactTimeout = currentConfigTimeout; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java index 149ea2286a..3251f3d047 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java @@ -20,67 +20,67 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; + import java.util.ArrayList; import java.util.List; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; - public class CambriaErrorResponse { - public static final int HTTP_OK = 200; + public static final int HTTP_OK = 200; - public static final int HTTP_INTERNAL_SERVER_ERROR = 500; + public static final int HTTP_INTERNAL_SERVER_ERROR = 500; - CambriaOperationStatus operationStatus; - Integer httpCode; - List<String> variables = new ArrayList<String>(); + CambriaOperationStatus operationStatus; + Integer httpCode; + List<String> variables = new ArrayList<String>(); - public CambriaErrorResponse() { - super(); - } + public CambriaErrorResponse() { + super(); + } - public CambriaErrorResponse(CambriaOperationStatus operationStatus) { - super(); - this.operationStatus = operationStatus; - } + public CambriaErrorResponse(CambriaOperationStatus operationStatus) { + super(); + this.operationStatus = operationStatus; + } - public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) { - super(); - this.operationStatus = operationStatus; - this.httpCode = httpCode; - } + public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) { + super(); + this.operationStatus = operationStatus; + this.httpCode = httpCode; + } - public CambriaOperationStatus getOperationStatus() { - return operationStatus; - } + public CambriaOperationStatus getOperationStatus() { + return operationStatus; + } - public void setOperationStatus(CambriaOperationStatus operationStatus) { - this.operationStatus = operationStatus; - } + public void setOperationStatus(CambriaOperationStatus operationStatus) { + this.operationStatus = operationStatus; + } - public Integer getHttpCode() { - return httpCode; - } + public Integer getHttpCode() { + return httpCode; + } - public void setHttpCode(Integer httpCode) { - this.httpCode = httpCode; - } + public void setHttpCode(Integer httpCode) { + this.httpCode = httpCode; + } - public void addVariable(String variable) { - variables.add(variable); - } + public void addVariable(String variable) { + variables.add(variable); + } - public List<String> getVariables() { - return variables; - } + public List<String> getVariables() { + return variables; + } - public void setVariables(List<String> variables) { - this.variables = variables; - } + public void setVariables(List<String> variables) { + this.variables = variables; + } - @Override - public String toString() { - return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]"; - } + @Override + public String toString() { + return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java index c496715a02..d6fee9a9d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java @@ -20,25 +20,7 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import com.att.nsa.cambria.client.CambriaBatchingPublisher; @@ -53,574 +35,591 @@ import com.att.nsa.cambria.client.CambriaConsumer; import com.att.nsa.cambria.client.CambriaIdentityManager; import com.att.nsa.cambria.client.CambriaPublisher.message; import com.att.nsa.cambria.client.CambriaTopicManager; +import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; - import fj.data.Either; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Component("cambriaHandler") public class CambriaHandler { - private static Logger logger = LoggerFactory.getLogger(CambriaHandler.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(CambriaHandler.class); + + private static final String PARTITION_KEY = "asdc" + "aa"; + + private final String SEND_NOTIFICATION = "send notification"; + + private Gson gson = new Gson(); + + private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionStatusTopic().getConsumerId(); + + + + /** + * process the response error from Cambria client + * + * @param message + * @return + */ + private Integer processMessageException(String message) { + + String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" }; + + Integer result = checkPattern(patterns[0], message, 2); + if (result != null) { + return result; + } + result = checkPattern(patterns[1], message, 2); + + return result; + + } + + /** + * check whether the message has a match with a given pattern inside it + * + * @param patternStr + * @param message + * @param groupIndex + * @return + */ + private Integer checkPattern(String patternStr, String message, int groupIndex) { + Integer result = null; + + Pattern pattern = Pattern.compile(patternStr); + Matcher matcher = pattern.matcher(message); + boolean find = matcher.find(); + if (find) { + String httpCode = matcher.group(groupIndex); + if (httpCode != null) { + try { + result = Integer.valueOf(httpCode); + } catch (NumberFormatException e) { + logger.debug("Failed to parse http code {}", httpCode); + } + } + } + return result; + } + + /** + * retrieve all topics from U-EB server + * + * @param hostSet + * @return + */ + public Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet) { + + CambriaTopicManager createTopicManager = null; + try { + + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet)); + + Set<String> topics = createTopicManager.getTopics(); + + if (topics == null || true == topics.isEmpty()) { + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null); + return Either.right(cambriaErrorResponse); + } + + return Either.left(topics); + + } catch (IOException | GeneralSecurityException e) { + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + logger.debug("Failed to fetch topics from U-EB server", e); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics"); + + return Either.right(cambriaErrorResponse); + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + } + + /** + * process the error message from Cambria client. + * + * set Cambria status and http code in case we succeed to fetch it + * + * @return + */ + private CambriaErrorResponse processError(Exception e) { + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(); + + Integer httpCode = processMessageException(e.getMessage()); + + if (httpCode != null) { + cambriaErrorResponse.setHttpCode(httpCode); + switch (httpCode.intValue()) { + + case 401: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR); + break; + case 409: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST); + break; + case 500: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR); + break; + default: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); + } + } else { + + boolean found = false; + Throwable throwable = e.getCause(); + if (throwable != null) { + String message = throwable.getMessage(); + + Throwable cause = throwable.getCause(); + + if (cause != null) { + Class<?> clazz = cause.getClass(); + String className = clazz.getName(); + if (className.endsWith("UnknownHostException")) { + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR); + cambriaErrorResponse.addVariable(message); + found = true; + } + } + } + + if (false == found) { + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); + cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + + return cambriaErrorResponse; + } + + /** + * write the error to the log + * + * @param cambriaErrorResponse + * @param errorMessage + * @param methodName + * @param operationDesc + */ + private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) { + + String httpCode = cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode()); + + switch (cambriaErrorResponse.getOperationStatus()) { + case UNKNOWN_HOST_ERROR: + String hostname = cambriaErrorResponse.getVariables().get(0); + BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode); + break; + case AUTHENTICATION_ERROR: + BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode); + break; + case CONNNECTION_ERROR: + BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode); + break; + + case INTERNAL_SERVER_ERROR: + BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc); + break; + default: + break; + } + + } + + /** + * create a topic if it does not exists in the topicsList + * + * @param hostSet + * - list of U-EB servers + * @param apiKey + * @param secretKey + * @param topicName + * - topic to create + * @param partitionCount + * @param replicationCount + * @return + */ + public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) { + + CambriaTopicManager createTopicManager = null; + try { + + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey)); + + createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); + + } catch (HttpException | IOException | GeneralSecurityException e) { + + logger.debug("Failed to create topic {}", topicName, e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) { + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic"); + } + + return cambriaErrorResponse; + + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + return new CambriaErrorResponse(CambriaOperationStatus.OK); + + } + + public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { + CambriaTopicManager createTopicManager = null; + try { + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); + + if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { + createTopicManager.revokeProducer(topicName, subscriberApiKey); + } else { + createTopicManager.revokeConsumer(topicName, subscriberApiKey); + } + + } catch (HttpObjectNotFoundException | GeneralSecurityException e) { + logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); + return cambriaErrorResponse; + + } catch (HttpException | IOException e) { + logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase()); + + return cambriaErrorResponse; + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + return cambriaErrorResponse; + } + + /** + * + * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER + * + * @param hostSet + * @param managerApiKey + * @param managerSecretKey + * @param subscriberApiKey + * @param subscriberTypeEnum + * @param topicName + * @return + */ + public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { + + CambriaTopicManager createTopicManager = null; + try { + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); + + if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { + createTopicManager.allowProducer(topicName, subscriberApiKey); + } else { + createTopicManager.allowConsumer(topicName, subscriberApiKey); + } + + } catch (HttpObjectNotFoundException | GeneralSecurityException e) { + logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); + return cambriaErrorResponse; + + } catch (HttpException | IOException e) { + logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase()); + + return cambriaErrorResponse; + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + return cambriaErrorResponse; + } + + /** + * create and retrieve a Cambria Consumer for a specific topic + * + * @param hostSet + * @param topicName + * @param apiKey + * @param secretKey + * @param consumerId + * @param consumerGroup + * @param timeoutMS + * @return + * @throws Exception + */ + public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception { + + CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHosts(hostSet).waitAtServer(timeoutMS).build(); + consumer.setApiCredentials(apiKey, secretKey); + return consumer; + } + + public void closeConsumer(CambriaConsumer consumer) { + + if (consumer != null) { + consumer.close(); + } + + } + + /** + * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error) + * + * @param topicConsumer + * @return + */ + public Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) { + + try { + Iterable<String> messages = topicConsumer.fetch(); + if (messages == null) { + messages = new ArrayList<String>(); + } + return Either.left(messages); + + } catch (IOException e) { + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage()); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic"); + + return Either.right(cambriaErrorResponse); + + } catch (Exception e) { + logger.debug("Failed to fetch from U-EB topic", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); + return Either.right(cambriaErrorResponse); + } + } + + /** + * Publish notification message to a given queue + * + * @param topicName + * @param uebPublicKey + * @param uebSecretKey + * @param uebServers + * @param data + * @return + */ + public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data) { + + CambriaBatchingPublisher createSimplePublisher = null; + + try { + + String json = gson.toJson(data); + logger.trace("Before sending notification data {} to topic {}", json, topicName); + + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - private static final String PARTITION_KEY = "asdc" + "aa"; - - private final String SEND_NOTIFICATION = "send notification"; - - private Gson gson = new Gson(); - - public static boolean useHttpsWithDmaap = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().isUseHttpsWithDmaap(); + int result = createSimplePublisher.send(PARTITION_KEY, json); + try { + Thread.sleep(1 * 1000); + } catch (InterruptedException e) { + logger.debug("Failed during sleep after sending the message.", e); + } - /** - * process the response error from Cambria client - * - * @param message - * @return - */ - private Integer processMessageException(String message) { - - String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" }; - - Integer result = checkPattern(patterns[0], message, 2); - if (result != null) { - return result; - } - result = checkPattern(patterns[1], message, 2); - - return result; - - } - - /** - * check whether the message has a match with a given pattern inside it - * - * @param patternStr - * @param message - * @param groupIndex - * @return - */ - private Integer checkPattern(String patternStr, String message, int groupIndex) { - Integer result = null; - - Pattern pattern = Pattern.compile(patternStr); - Matcher matcher = pattern.matcher(message); - boolean find = matcher.find(); - if (find) { - String httpCode = matcher.group(groupIndex); - if (httpCode != null) { - try { - result = Integer.valueOf(httpCode); - } catch (NumberFormatException e) { - logger.debug("Failed to parse http code {}", httpCode); - } - } - } - return result; - } - - /** - * retrieve all topics from U-EB server - * - * @param hostSet - * @return - */ - public Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet) { - - CambriaTopicManager createTopicManager = null; - try { - - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet)); - - Set<String> topics = createTopicManager.getTopics(); - - if (topics == null || true == topics.isEmpty()) { - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null); - return Either.right(cambriaErrorResponse); - } - - return Either.left(topics); - - } catch (IOException | GeneralSecurityException e) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - logger.debug("Failed to fetch topics from U-EB server", e); - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics"); - - return Either.right(cambriaErrorResponse); - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - } - - /** - * process the error message from Cambria client. - * - * set Cambria status and http code in case we succeed to fetch it - * - * @return - */ - private CambriaErrorResponse processError(Exception e) { - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(); - - Integer httpCode = processMessageException(e.getMessage()); - - if (httpCode != null) { - cambriaErrorResponse.setHttpCode(httpCode); - switch (httpCode.intValue()) { - - case 401: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR); - break; - case 409: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST); - break; - case 500: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR); - break; - default: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); - } - } else { - - boolean found = false; - Throwable throwable = e.getCause(); - if (throwable != null) { - String message = throwable.getMessage(); - - Throwable cause = throwable.getCause(); - - if (cause != null) { - Class<?> clazz = cause.getClass(); - String className = clazz.getName(); - if (className.endsWith("UnknownHostException")) { - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR); - cambriaErrorResponse.addVariable(message); - found = true; - } - } - } - - if (false == found) { - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); - cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - } - - return cambriaErrorResponse; - } - - /** - * write the error to the log - * - * @param cambriaErrorResponse - * @param errorMessage - * @param methodName - * @param operationDesc - */ - private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) { - - String httpCode = (cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode())); - - switch (cambriaErrorResponse.getOperationStatus()) { - case UNKNOWN_HOST_ERROR: - String hostname = cambriaErrorResponse.getVariables().get(0); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebUnkownHostError, methodName, hostname); - BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode); - break; - case AUTHENTICATION_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebAuthenticationError, methodName, httpCode); - BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode); - break; - case CONNNECTION_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebConnectionError, methodName, httpCode); - BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode); - break; - - case INTERNAL_SERVER_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, methodName, operationDesc); - BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc); - break; - default: - break; - } - - } - - /** - * create a topic if it does not exists in the topicsList - * - * @param hostSet - * - list of U-EB servers - * @param apiKey - * @param secretKey - * @param topicName - * - topic to create - * @param partitionCount - * @param replicationCount - * @return - */ - public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) { - - CambriaTopicManager createTopicManager = null; - try { - - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey)); - - createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); - - } catch (HttpException | IOException | GeneralSecurityException e) { - - logger.debug("Failed to create topic {}", topicName, e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) { - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic"); - } - - return cambriaErrorResponse; - - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - return new CambriaErrorResponse(CambriaOperationStatus.OK); - - } - - public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) { - CambriaTopicManager createTopicManager = null; - try { - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); - - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { - createTopicManager.revokeProducer(topicName, subscriberApiKey); - } else { - createTopicManager.revokeConsumer(topicName, subscriberApiKey); - } - - } catch (HttpObjectNotFoundException | GeneralSecurityException e) { - logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - return cambriaErrorResponse; - - } catch (HttpException | IOException e) { - logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase()); - - return cambriaErrorResponse; - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - return cambriaErrorResponse; - } - - /** - * - * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER - * - * @param hostSet - * @param topicName - * @param managerApiKey - * @param managerSecretKey - * @param subscriberApiKey - * @param subscriberTypeEnum - * @return - */ - public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) { - - CambriaTopicManager createTopicManager = null; - try { - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); - - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { - createTopicManager.allowProducer(topicName, subscriberApiKey); - } else { - createTopicManager.allowConsumer(topicName, subscriberApiKey); - } - - } catch (HttpObjectNotFoundException | GeneralSecurityException e) { - logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - return cambriaErrorResponse; - - } catch (HttpException | IOException e) { - logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase()); - - return cambriaErrorResponse; - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - return cambriaErrorResponse; - } - - /** - * create and retrieve a Cambria Consumer for a specific topic - * - * @param hostSet - * @param topicName - * @param apiKey - * @param secretKey - * @param consumerId - * @param consumerGroup - * @param timeoutMS - * @return - * @throws Exception - */ - public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception { - - CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(hostSet).withSocketTimeout(timeoutMS).build(); - consumer.setApiCredentials(apiKey, secretKey); - return consumer; - } - - public void closeConsumer(CambriaConsumer consumer) { - - if (consumer != null) { - consumer.close(); - } - - } - - /** - * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error) - * - * @param topicConsumer - * @return - */ - public Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) { - - try { - Iterable<String> messages = topicConsumer.fetch(); - if (messages == null) { - messages = new ArrayList<String>(); - } - return Either.left(messages); - - } catch (IOException e) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage()); - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic"); - - return Either.right(cambriaErrorResponse); - - } catch (Exception e) { - logger.debug("Failed to fetch from U-EB topic", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); - return Either.right(cambriaErrorResponse); - } - } + return response; - /** - * Publish notification message to a given queue - * - * @param topicName - * @param uebPublicKey - * @param uebSecretKey - * @param uebServers - * @param data - * @return - */ - public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data) { + } catch (IOException | GeneralSecurityException e) { + logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); - CambriaBatchingPublisher createSimplePublisher = null; + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); - try { + CambriaErrorResponse cambriaErrorResponse = processError(e); - String json = gson.toJson(data); - logger.trace("Before sending notification data {} to topic {}", json, topicName); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build(); - createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - - int result = createSimplePublisher.send(PARTITION_KEY, json); - - try { - Thread.sleep(1 * 1000); - } catch (InterruptedException e) { - logger.debug("Failed during sleep after sending the message.", e); - } - - logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - - CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - - return response; + return cambriaErrorResponse; + } finally { + if (createSimplePublisher != null) { + logger.debug("Before closing publisher"); + createSimplePublisher.close(); + logger.debug("After closing publisher"); + } + } + } - } catch (IOException | GeneralSecurityException e) { - logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); + public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + CambriaBatchingPublisher createSimplePublisher = null; - CambriaErrorResponse cambriaErrorResponse = processError(e); + CambriaErrorResponse response = null; + try { - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION); + String json = gson.toJson(data); + logger.debug("Before sending notification data {} to topic {}", json, topicName); - return cambriaErrorResponse; - } finally { - if (createSimplePublisher != null) { - logger.debug("Before closing publisher"); - createSimplePublisher.close(); - logger.debug("After closing publisher"); - } - } - } + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - private String convertListToString(List<String> list) { - StringBuilder builder = new StringBuilder(); + int result = createSimplePublisher.send(PARTITION_KEY, json); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - builder.append(list.get(i)); - if (i < list.size() - 1) { - builder.append(","); - } - } - } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.debug("Failed during sleep after sending the message.", e); + } - return builder.toString(); - } + logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout) { + } catch (IOException | GeneralSecurityException e) { + logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); - CambriaBatchingPublisher createSimplePublisher = null; + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); - CambriaErrorResponse response = null; - try { + response = processError(e); - String json = gson.toJson(data); - logger.debug("Before sending notification data {} to topic {}", json, topicName); + writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build(); - createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); + return response; - int result = createSimplePublisher.send(PARTITION_KEY, json); + } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - logger.debug("Failed during sleep after sending the message.", e); - } + logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); + try { + List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS); + if (messagesInQ != null && false == messagesInQ.isEmpty()) { + logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size()); + response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); + } else { + logger.debug("No message left in the queue after closing cambria publisher"); + response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + } + } catch (IOException | InterruptedException e) { + logger.debug("Failed to close cambria publisher", e); + response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); + } + logger.debug("After closing publisher"); - logger.debug("After sending notification data to topic {}. result is {}", topicName, result); + return response; - } catch (IOException | GeneralSecurityException e) { - logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); + } - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + public CambriaErrorResponse getApiKey(String server, String apiKey) { - response = processError(e); + CambriaErrorResponse response = null; - writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION); + List<String> hostSet = new ArrayList<>(); + hostSet.add(server); + try { + CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); + createIdentityManager.getApiKey(apiKey); - return response; + response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - } + } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { + logger.debug("Failed to fetch api key {} from server {}", apiKey, server, e); - logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); - try { - List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS); - if (messagesInQ != null && false == messagesInQ.isEmpty()) { - logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size()); - response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); - } else { - logger.debug("No message left in the queue after closing cambria publisher"); - response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - } - } catch (IOException | InterruptedException e) { - logger.debug("Failed to close cambria publisher", e); - response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); - } - logger.debug("After closing publisher"); + response = processError(e); - return response; + } - } + return response; + } - public CambriaErrorResponse getApiKey(String server, String apiKey) { + public Either<ApiCredential, CambriaErrorResponse> createUebKeys(List<String> hostSet) { + Either<ApiCredential, CambriaErrorResponse> result; - CambriaErrorResponse response = null; + try { + CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); - List<String> hostSet = new ArrayList<>(); - hostSet.add(server); - CambriaIdentityManager createIdentityManager = null; - try { - createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); - createIdentityManager.getApiKey(apiKey); - response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + String description = String.format("ASDC Key for %s", CONSUMER_ID); + ApiCredential credential = createIdentityManager.createApiKey("", description); + createIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); + result = Either.left(credential); - } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { - logger.debug("Failed to fetch api key {} from server ", apiKey, server, e); + } catch (Exception e) { + logger.debug("Failed to create ueb keys for servers {}",hostSet, e); - response = processError(e); + result = Either.right(processError(e)); - } + } - return response; - } + return result; + } - private static <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<? extends CambriaClient> client) throws MalformedURLException, GeneralSecurityException { - if (useHttpsWithDmaap) { - client.usingHttps(); - } - return (T)client.build(); - } + @VisibleForTesting + <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<? extends CambriaClient> client) throws MalformedURLException, GeneralSecurityException { + return (T)client.build(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java new file mode 100644 index 0000000000..94fff3cfaa --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.api.DME2Manager; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.aft.dme2.iterator.factory.DME2EndpointIteratorFactory; + +import org.springframework.stereotype.Component; + +@Component +public class DME2EndpointIteratorCreator { + + public DME2EndpointIterator create(String lookupURI) throws DME2Exception { + // Initializing DME2Manager instance + DME2Manager manager = DME2Manager.getDefaultInstance(); + // Returning an instance of the DME2EndpointIteratorFactory + return (DME2EndpointIterator) DME2EndpointIteratorFactory.getInstance().getIterator(lookupURI, null, null, manager); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java deleted file mode 100644 index 5e4c08275f..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.distribution.engine; - -public enum DeConfigurationStatus { - - OK(""), MISSING_CONFIGURATION(""); - - private String description; - - DeConfigurationStatus(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java index bd3d74e323..7d2d4680b5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java @@ -20,361 +20,340 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.util.YamlToObjectConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @Component("distributionEngine") public class DistributionEngine implements IDistributionEngine { - public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); - - public static void main(String[] args) { - - List<String> servers = new ArrayList<>(); - - servers.add("uebsb91kcdc.it.att.com:3904"); - servers.add("uebsb91kcdc.it.att.com:3904"); - servers.add("uebsb91kcdc.it.att.com:3904"); - - YamlToObjectConverter converter = new YamlToObjectConverter(); - DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class); - - DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null); - distributionEngineInitTask.startTask(); - - } - - @javax.annotation.Resource - private ComponentsUtils componentUtils; - - @javax.annotation.Resource - private DistributionNotificationSender distributionNotificationSender; - - @javax.annotation.Resource - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - - @javax.annotation.Resource - private DistributionEngineClusterHealth distributionEngineClusterHealth; - - private static Logger logger = LoggerFactory.getLogger(DistributionEngine.class.getName()); - - private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<String, DistributionEngineInitTask>(); - private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<String, DistributionEnginePollingTask>(); - - private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<String, AtomicBoolean>(); - - @Override - public boolean isActive() { - - if (true == envNamePerInitTask.isEmpty()) { - return false; - } - - for (DistributionEngineInitTask task : envNamePerInitTask.values()) { - boolean active = task.isActive(); - if (active == false) { - return false; - } - } - return true; - } - - @PostConstruct - private void init() { - - logger.trace("Enter init method of DistributionEngine"); - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine(); - logger.debug("Distribution engine activation parameter is {}", startDistributionEngine); - if (false == startDistributionEngine) { - logger.info("The disribution engine is disabled"); - - this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled(); - - return; - } - - boolean isValidConfig = validateConfiguration(distributionEngineConfiguration); - - if (false == isValidConfig) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); - - this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError(); - return; - } - - List<String> environments = distributionEngineConfiguration.getEnvironments(); - - for (String envName : environments) { - - DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(distributionEngineConfiguration, envName, componentUtils, distributionEngineClusterHealth); - - logger.debug("Init task for environment {}", envName); - - AtomicBoolean status = new AtomicBoolean(false); - envNamePerStatus.put(envName, status); - DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask); - distributionEngineInitTask.startTask(); - envNamePerInitTask.put(envName, distributionEngineInitTask); - envNamePerPollingTask.put(envName, distributionEnginePollingTask); - } - - logger.debug("Init UEB health check"); - distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); - - logger.trace("Exit init method of DistributionEngine"); - - } - - @PreDestroy - public void shutdown() { - logger.info("distribution engine shutdown - start"); - if (envNamePerInitTask != null) { - for (DistributionEngineInitTask task : envNamePerInitTask.values()) { - task.destroy(); - } - } - if (envNamePerPollingTask != null) { - for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) { - task.destroy(); - } - } - - } - - /** - * validate mandatory configuration parameters received - * - * @param deConfiguration - * @return - */ - protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) { - - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - boolean result = true; - result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result; - result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result; - result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result; - result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result; - result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result; - result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result; - result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result; - result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result; - - return result; - } - - private boolean isValidServers(List<String> uebServers, String methodName, String paramName) { - - if (uebServers == null || uebServers.size() == 0) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - - if (uebServers.size() < 2) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeConfigurationInvalidListSizeError, methodName, paramName, "2"); - BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2); - return false; - } - - for (String serverFqdn : uebServers) { - if (false == isValidFqdn(serverFqdn)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, methodName, paramName, serverFqdn); - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn); - return false; - } - } - - return true; - } - - private boolean isValidFqdn(String serverFqdn) { - - try { - Matcher matcher = FQDN_PATTERN.matcher(serverFqdn); - return matcher.matches(); - - } catch (Exception e) { - logger.debug("Failed to match value of address {}", serverFqdn, e); - return false; - } - - } - - private boolean isEmptyParam(String param) { - - if (param == null || true == param.isEmpty()) { - return true; - } - - return false; - } - - private boolean isValidParam(String paramValue, String methodName, String paramName) { - - if (isEmptyParam(paramValue)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isValidParam(List<String> paramValue, String methodName, String paramName) { - - if (isEmptyList(paramValue)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isValidObject(Object paramValue, String methodName, String paramName) { - - if (paramValue == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isEmptyList(List<String> list) { - if (list == null || true == list.isEmpty()) { - return true; - } - return false; - } - - private String getEnvironmentErrorDescription(StorageOperationStatus status) { - - switch (status) { - case DISTR_ENVIRONMENT_NOT_AVAILABLE: - return "environment is unavailable"; - case DISTR_ENVIRONMENT_NOT_FOUND: - return "environment is not configured in our system"; - case DISTR_ENVIRONMENT_SENT_IS_INVALID: - return "environment name is invalid"; - - default: - return "unkhown"; - - } - } - - public StorageOperationStatus isEnvironmentAvailable(String envName) { - - if (envName == null || true == envName.isEmpty()) { - - return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID; - } - - AtomicBoolean status = envNamePerStatus.get(envName); - if (status == null) { - return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND; - } - - if (false == status.get()) { - return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE; - } - return StorageOperationStatus.OK; - } + private static final Logger LOGGER = LoggerFactory.getLogger(DistributionEngine.class); + private static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); - public StorageOperationStatus isEnvironmentAvailable() { + @Autowired + private EnvironmentsEngine environmentsEngine; - String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + @Resource + private DistributionNotificationSender distributionNotificationSender; - return isEnvironmentAvailable(envName); - } + @Resource + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Override - public void disableEnvironment(String envName) { - // TODO disable tasks - AtomicBoolean status = envNamePerStatus.get(envName); - status.set(false); - } + @Resource + private DistributionEngineClusterHealth distributionEngineClusterHealth; - @Override - public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + @Resource + private ServiceDistributionValidation serviceDistributionValidation; - logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); + private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>(); + private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>(); + private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); - DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + /** + * The main method for testing only + * @param args + */ + public static void main(String[] args) { - String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName(); - String topicName = DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName); + List<String> servers = new ArrayList<>(); + String server = "uebsb91kcdc.it.att.com:3904"; + servers.add(server); + servers.add(server); + servers.add(server); - StorageOperationStatus sendNotification = distributionNotificationSender.sendNotification(topicName, distributionId, deConfiguration, envName, notificationData, service, userId, modifierName); + YamlToObjectConverter converter = new YamlToObjectConverter(); + DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class); - logger.debug("Finish notifyService. status is {}", sendNotification); + DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null, null); + distributionEngineInitTask.startTask(); + + } - return sendNotification; - } + @Override + public boolean isActive() { - @Override - public Either<INotificationData, StorageOperationStatus> isReadyForDistribution(Service service, String distributionId, String envName) { - StorageOperationStatus status = isEnvironmentAvailable(envName); - if (status != StorageOperationStatus.OK) { - String envErrorDec = getEnvironmentErrorDescription(status); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, - "Environment name " + envName + " is not available. Reason : " + envErrorDec); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec); - return Either.right(status); - } + if (envNamePerInitTask.isEmpty()) { + return false; + } - Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifactsStatus = serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service); - if (isServiceContainsDeploymentArtifactsStatus.isRight()) { - StorageOperationStatus operationStatus = isServiceContainsDeploymentArtifactsStatus.right().value(); - return Either.right(operationStatus); - } else { - Boolean isDeploymentArtifactExists = isServiceContainsDeploymentArtifactsStatus.left().value(); - if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) { - return Either.right(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND); - } - } + for (DistributionEngineInitTask task : envNamePerInitTask.values()) { + boolean active = task.isActive(); + if (!active) { + return false; + } + } + return true; + } - INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId); - value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service); + @PostConstruct + private void init() { + + LOGGER.trace("Enter init method of DistributionEngine"); + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine(); + LOGGER.debug("Distribution engine activation parameter is {}", startDistributionEngine); + if (!startDistributionEngine) { + LOGGER.info("The disribution engine is disabled"); - return Either.left(value); - } + this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled(); + + return; + } + + boolean isValidConfig = validateConfiguration(distributionEngineConfiguration); + + if (!isValidConfig) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); + + this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError(); + return; + } + + List<String> environments = distributionEngineConfiguration.getEnvironments(); + + for (String envName : environments) { + LOGGER.debug("init task for environment {}", envName); + AtomicBoolean status = new AtomicBoolean(false); + envNamePerStatus.put(envName, status); + environmentsEngine.connectUebTopicForDistributionConfTopic(envName, status, envNamePerInitTask, envNamePerPollingTask); + } + + LOGGER.debug("init UEB health check"); + distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + + LOGGER.trace("Exit init method of DistributionEngine"); + + } + + @PreDestroy + public void shutdown() { + LOGGER.info("distribution engine shutdown - start"); + if (envNamePerInitTask != null) { + for (DistributionEngineInitTask task : envNamePerInitTask.values()) { + task.destroy(); + } + } + if (envNamePerPollingTask != null) { + for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) { + task.destroy(); + } + } + + } + + /** + * validate mandatory configuration parameters received + * + * @param deConfiguration + * @return + */ + protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) { + + String methodName = "validateConfiguration"; + + boolean result = true; + result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result; + result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result; + result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result; + result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result; + result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result; + result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result; + result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result; + result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result; + + return result; + } + + private boolean isValidServers(List<String> uebServers, String methodName, String paramName) { + + if (uebServers == null || uebServers.isEmpty()) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + + if (uebServers.size() < 2) { + BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2); + return false; + } + + for (String serverFqdn : uebServers) { + if (!isValidFqdn(serverFqdn)) { + BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn); + return false; + } + } + + return true; + } + + private boolean isValidFqdn(String serverFqdn) { + + try { + Matcher matcher = FQDN_PATTERN.matcher(serverFqdn); + return matcher.matches(); + + } catch (Exception e) { + LOGGER.debug("Failed to match value of address {}", serverFqdn, e); + return false; + } + } + + private boolean isValidParam(String paramValue, String methodName, String paramName) { + + if (StringUtils.isEmpty(paramValue)) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + } + + private boolean isValidParam(List<String> paramValue, String methodName, String paramName) { + + if (CollectionUtils.isEmpty(paramValue)) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + } + + private boolean isValidObject(Object paramValue, String methodName, String paramName) { + + if (paramValue == null) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + + } + + private String getEnvironmentErrorDescription(StorageOperationStatus status) { + + switch (status) { + case DISTR_ENVIRONMENT_NOT_AVAILABLE: + return "environment is unavailable"; + case DISTR_ENVIRONMENT_NOT_FOUND: + return "environment is not configured in our system"; + case DISTR_ENVIRONMENT_SENT_IS_INVALID: + return "environment name is invalid"; + default: + return "unkhown"; + } + } + + @Override + public StorageOperationStatus isEnvironmentAvailable(String envName) { + + if (envName == null || envName.isEmpty()) { + + return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID; + } + + AtomicBoolean status = envNamePerStatus.get(envName); + if (status == null) { + return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND; + } + + if (!status.get()) { + return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE; + } + return StorageOperationStatus.OK; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable() { + + String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + + return isEnvironmentAvailable(envName); + } + + @Override + public void disableEnvironment(String envName) { + AtomicBoolean status = envNamePerStatus.get(envName); + status.set(false); + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + return notifyService(distributionId, service, notificationData, envName, envName, userId, modifierName); + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) { + LOGGER.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); + String topicName = buildTopicName(envName); + ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId)) + .map(EnvironmentMessageBusData::new) + .map(messageBusData -> distributionNotificationSender.sendNotification(topicName, distributionId, messageBusData, notificationData, service, userId, modifierName)) + .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE); + LOGGER.debug("Finish notifyService. status is {}", notifyServiceStatus); + return notifyServiceStatus; + } + + private String buildTopicName(String envName) { + DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName(); + return DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName); + } + + @Override + public StorageOperationStatus isReadyForDistribution(Service service, String envName) { + StorageOperationStatus status = isEnvironmentAvailable(envName); + if (status != StorageOperationStatus.OK) { + String envErrorDec = getEnvironmentErrorDescription(status); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec); + return status; + } + + return verifyServiceHasDeploymentArtifacts(service); + } + + @Override + public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) { + if (!serviceDistributionArtifactsBuilder.verifyServiceContainsDeploymentArtifacts(service)) { + return StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND; + } + return StorageOperationStatus.OK; + } + + @Override + public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) { + return environmentsEngine.getEnvironmentById(opEnvId); + } + + @Override + public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) { + INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId, workloadContext); + value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service); + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java index 85a868f156..9599879006 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java @@ -20,22 +20,6 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; @@ -47,311 +31,318 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; + @Component("distribution-engine-cluster-health") public class DistributionEngineClusterHealth { - protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck"; + protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck"; - private static Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT); + private static final Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT); - private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; + private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; - boolean lastHealthState = false; + boolean lastHealthState = false; - Object lockOject = new Object(); + Object lockOject = new Object(); - private long reconnectInterval = 5; + private long reconnectInterval = 5; - private long healthCheckReadTimeout = 20; + private long healthCheckReadTimeout = 20; - private static Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class); - private List<String> uebServers = null; + private List<String> uebServers = null; - private String publicApiKey = null; + private String publicApiKey = null; - public enum HealthCheckInfoResult { + public enum HealthCheckInfoResult { - OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), - UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), - NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), - DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); + OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), + NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), + DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); - private HealthCheckInfo healthCheckInfo; + private HealthCheckInfo healthCheckInfo; - HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { - this.healthCheckInfo = healthCheckInfo; - } + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } - public HealthCheckInfo getHealthCheckInfo() { - return healthCheckInfo; - } + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } - } + } - private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); - private Map<String, AtomicBoolean> envNamePerStatus = null; + private Map<String, AtomicBoolean> envNamePerStatus = null; - private ScheduledFuture<?> scheduledFuture = null; + private ScheduledFuture<?> scheduledFuture = null; - ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "UEB-Health-Check-Task"); - } - }); + ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "UEB-Health-Check-Task"); + } + }); - HealthCheckScheduledTask healthCheckScheduledTask = null; + HealthCheckScheduledTask healthCheckScheduledTask = null; - public enum ClusterStatusDescription { + public enum ClusterStatusDescription { - OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"); + OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"); - private String desc; + private String desc; - ClusterStatusDescription(String desc) { - this.desc = desc; - } + ClusterStatusDescription(String desc) { + this.desc = desc; + } - public String getDescription() { - return desc; - } + public String getDescription() { + return desc; + } - } + } - /** - * Health Check Task Scheduler. - * - * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server. - * - * - * @author esofer - * - */ - public class HealthCheckScheduledTask implements Runnable { + /** + * Health Check Task Scheduler. + * + * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server. + * + * + * @author esofer + * + */ + public class HealthCheckScheduledTask implements Runnable { - List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>(); + List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>(); - public HealthCheckScheduledTask(List<String> uebServers) { + public HealthCheckScheduledTask(List<String> uebServers) { - logger.debug("Create health check calls for servers {}", uebServers); - if (uebServers != null) { - for (String server : uebServers) { - healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey)); - } - } - } + logger.debug("Create health check calls for servers {}", uebServers); + if (uebServers != null) { + for (String server : uebServers) { + healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey)); + } + } + } - @Override - public void run() { + @Override + public void run() { - healthLogger.trace("Executing UEB Health Check Task - Start"); + healthLogger.trace("Executing UEB Health Check Task - Start"); - boolean healthStatus = verifyAtLeastOneEnvIsUp(); + boolean healthStatus = verifyAtLeastOneEnvIsUp(); - if (true == healthStatus) { - boolean queryUebStatus = queryUeb(); - if (queryUebStatus == lastHealthState) { - return; - } + if (true == healthStatus) { + boolean queryUebStatus = queryUeb(); + if (queryUebStatus == lastHealthState) { + return; + } - synchronized (lockOject) { - if (queryUebStatus != lastHealthState) { - logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); - lastHealthState = queryUebStatus; - logAlarm(lastHealthState); - if (true == queryUebStatus) { - healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); - } else { - healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); - } - } - } - } else { - healthLogger.trace("Not all UEB Environments are up"); - } - - } - - /** - * verify that at least one environment is up. - * - */ - private boolean verifyAtLeastOneEnvIsUp() { - - boolean healthStatus = false; + synchronized (lockOject) { + if (queryUebStatus != lastHealthState) { + logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); + lastHealthState = queryUebStatus; + logAlarm(lastHealthState); + if (true == queryUebStatus) { + healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); + } else { + healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + } + } + } + } else { + healthLogger.trace("Not all UEB Environments are up"); + } + + } + + /** + * verify that at least one environment is up. + * + */ + private boolean verifyAtLeastOneEnvIsUp() { + + boolean healthStatus = false; - if (envNamePerStatus != null) { - Collection<AtomicBoolean> values = envNamePerStatus.values(); - if (values != null) { - for (AtomicBoolean status : values) { - if (true == status.get()) { - healthStatus = true; - break; - } - } - } - } - - return healthStatus; - } - - /** - * executor for the query itself - */ - ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "UEB-Health-Check-Thread"); - } - }); - - /** - * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers. - * - * - * @return - */ - private boolean queryUeb() { - - Boolean result = false; - int retryNumber = 1; - for (UebHealthCheckCall healthCheckCall : healthCheckCalls) { - try { - - healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer()); - - Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall); - result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS); - - healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result); - - if (result != null && true == result.booleanValue()) { - break; - } - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message); - healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e); - } - retryNumber++; - - } - - return result; - - } - - public List<UebHealthCheckCall> getHealthCheckCalls() { - return healthCheckCalls; - } - - } - - @PostConstruct - private void init() { - - logger.trace("Enter init method of DistributionEngineClusterHealth"); - - Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds(); - if (reconnectIntervalConfig != null) { - reconnectInterval = reconnectIntervalConfig.longValue(); - } - Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout(); - if (healthCheckReadTimeoutConfig != null) { - healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue(); - } - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - this.uebServers = distributionEngineConfiguration.getUebServers(); - this.publicApiKey = distributionEngineConfiguration.getUebPublicKey(); - - this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers); - - logger.trace("Exit init method of DistributionEngineClusterHealth"); - - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (healthCheckScheduler != null) { - healthCheckScheduler.shutdown(); - } - - } - - /** - * Start health check task. - * - * @param envNamePerStatus - * @param startTask - */ - public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) { - this.envNamePerStatus = envNamePerStatus; - - if (startTask == true && this.scheduledFuture == null) { - this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); - } - } - - public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) { - startHealthCheckTask(envNamePerStatus, true); - } - - private void logAlarm(boolean lastHealthState) { - if (lastHealthState == true) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery, UEB_HEALTH_CHECK_STR); - BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, UEB_HEALTH_CHECK_STR); - BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR); - } - } - - public HealthCheckInfo getHealthCheckInfo() { - return healthCheckInfo; - } - - /** - * change the health check to DISABLE - */ - public void setHealthCheckUebIsDisabled() { - healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo(); - } - - /** - * change the health check to NOT CONFGIURED - */ - public void setHealthCheckUebConfigurationError() { - healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo(); - } - - public void setHealthCheckOkAndReportInCaseLastStateIsDown() { - - if (lastHealthState == true) { - return; - } - synchronized (lockOject) { - if (lastHealthState == false) { - logger.debug("Going to update health check state to available"); - lastHealthState = true; - healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); - logAlarm(lastHealthState); - } - } - - } + if (envNamePerStatus != null) { + Collection<AtomicBoolean> values = envNamePerStatus.values(); + if (values != null) { + for (AtomicBoolean status : values) { + if (true == status.get()) { + healthStatus = true; + break; + } + } + } + } + + return healthStatus; + } + + /** + * executor for the query itself + */ + ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "UEB-Health-Check-Thread"); + } + }); + + /** + * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers. + * + * + * @return + */ + private boolean queryUeb() { + + Boolean result = false; + int retryNumber = 1; + for (UebHealthCheckCall healthCheckCall : healthCheckCalls) { + try { + + healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer()); + + Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall); + result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS); + + healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result); + + if (result != null && true == result.booleanValue()) { + break; + } + + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message); + healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e); + } + retryNumber++; + + } + + return result; + + } + + public List<UebHealthCheckCall> getHealthCheckCalls() { + return healthCheckCalls; + } + + } + + @PostConstruct + protected void init() { + + logger.trace("Enter init method of DistributionEngineClusterHealth"); + + Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds(); + if (reconnectIntervalConfig != null) { + reconnectInterval = reconnectIntervalConfig.longValue(); + } + Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout(); + if (healthCheckReadTimeoutConfig != null) { + healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue(); + } + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + this.uebServers = distributionEngineConfiguration.getUebServers(); + this.publicApiKey = distributionEngineConfiguration.getUebPublicKey(); + + this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers); + + logger.trace("Exit init method of DistributionEngineClusterHealth"); + + } + + @PreDestroy + protected void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (healthCheckScheduler != null) { + healthCheckScheduler.shutdown(); + } + + } + + /** + * Start health check task. + * + * @param envNamePerStatus + * @param startTask + */ + public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) { + this.envNamePerStatus = envNamePerStatus; + + if (startTask == true && this.scheduledFuture == null) { + this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); + } + } + + public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) { + startHealthCheckTask(envNamePerStatus, true); + } + + private void logAlarm(boolean lastHealthState) { + if (lastHealthState == true) { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR); + } + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + + /** + * change the health check to DISABLE + */ + public void setHealthCheckUebIsDisabled() { + healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo(); + } + + /** + * change the health check to NOT CONFGIURED + */ + public void setHealthCheckUebConfigurationError() { + healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo(); + } + + public void setHealthCheckOkAndReportInCaseLastStateIsDown() { + + if (lastHealthState == true) { + return; + } + synchronized (lockOject) { + if (lastHealthState == false) { + logger.debug("Going to update health check state to available"); + lastHealthState = true; + healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); + logAlarm(lastHealthState); + } + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java index 1eeaa1229e..1759f69b3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java @@ -20,274 +20,268 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; public class DistributionEngineInitTask implements Runnable { - public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine"; - public static final String ALREADY_EXISTS = "ALREADY_EXISTS"; - public static final String CONSUMER = "CONSUMER"; - public static final String PRODUCER = "PRODUCER"; - public static final String CREATED = "CREATED"; - public static final String FAILED = "FAILED"; - public static final Integer HTTP_OK = 200; - - private Long delayBeforeStartFlow = 0l; - private DistributionEngineConfiguration deConfiguration; - private String envName; - private long retryInterval; - private long currentRetryInterval; - private long maxInterval; - // private boolean active = false; - boolean maximumRetryInterval = false; - private AtomicBoolean status = null; - ComponentsUtils componentsUtils = null; - DistributionEnginePollingTask distributionEnginePollingTask = null; - - private CambriaHandler cambriaHandler = new CambriaHandler(); - - public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask) { - super(); - this.delayBeforeStartFlow = delayBeforeStartFlow; - this.deConfiguration = deConfiguration; - this.envName = envName; - this.retryInterval = deConfiguration.getInitRetryIntervalSec(); - this.currentRetryInterval = retryInterval; - this.maxInterval = deConfiguration.getInitMaxIntervalSec(); - this.status = status; - this.componentsUtils = componentsUtils; - this.distributionEnginePollingTask = distributionEnginePollingTask; - } - - private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); - - private static Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class.getName()); - - ScheduledFuture<?> scheduledFuture = null; - - public void startTask() { - if (scheduledExecutorService != null) { - Integer retryInterval = deConfiguration.getInitRetryIntervalSec(); - logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow); - this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS); - - } - } - - public void restartTask() { - - this.stopTask(); - - logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval); - - long lastCurrentInterval = currentRetryInterval; - incrementRetryInterval(); - - this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS); - - } - - protected void incrementRetryInterval() { - if (currentRetryInterval < maxInterval) { - currentRetryInterval *= 2; - if (currentRetryInterval > maxInterval) { - setMaxRetryInterval(); - } - } else { - setMaxRetryInterval(); - } - } - - private void setMaxRetryInterval() { - currentRetryInterval = maxInterval; - maximumRetryInterval = true; - logger.debug("Set next retry init interval to {}", maxInterval); - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - logger.debug("Stop reinit task. result = {}", result); - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); - } - scheduledFuture = null; - } - } - - public void destroy() { - this.stopTask(); - if (scheduledExecutorService != null) { - scheduledExecutorService.shutdown(); - } - } - - @Override - public void run() { - - boolean result = false; - result = initFlow(); - - if (true == result) { - this.stopTask(); - this.status.set(true); - if (this.distributionEnginePollingTask != null) { - String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName); - logger.debug("start polling distribution status topic {}", topicName); - this.distributionEnginePollingTask.startTask(topicName); - } - } else { - if (false == maximumRetryInterval) { - this.restartTask(); - } - } - } - - /** - * run initialization flow - * - * @return - */ - public boolean initFlow() { - - logger.trace("Start init flow for environment {}", this.envName); - - Set<String> topicsList = null; - Either<Set<String>, CambriaErrorResponse> getTopicsRes = null; - - getTopicsRes = cambriaHandler.getTopics(deConfiguration.getUebServers()); - if (getTopicsRes.isRight()) { - CambriaErrorResponse status = getTopicsRes.right().value(); - if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) { - topicsList = new HashSet<>(); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); - - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); - - return false; - } - } else { - topicsList = getTopicsRes.left().value(); - } - - String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName); - logger.debug("Going to handle topic {}", notificationTopic); - - boolean status = createTopicIfNotExists(topicsList, notificationTopic); - if (false == status) { - return false; - } - - CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER); - - CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus(); - - if (createStatus != CambriaOperationStatus.OK) { - return false; - } - - String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName); - logger.debug("Going to handle topic {}", statusTopic); - status = createTopicIfNotExists(topicsList, statusTopic); - if (false == status) { - return false; - } - - CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER); - - if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) { - return false; - } - - return true; - } - - private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) { - CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(deConfiguration.getUebServers(), topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebPublicKey(), subscriberType); - - String role = CONSUMER; - if (subscriberType == SubscriberTypeEnum.PRODUCER) { - role = PRODUCER; - } - auditRegistration(topicName, registerStatus, role); - return registerStatus; - } - - private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) { - if (componentsUtils != null) { - Integer httpCode = registerProducerStatus.getHttpCode(); - String httpCodeStr = String.valueOf(httpCode); - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, deConfiguration.getUebPublicKey(), httpCodeStr); - } - } - - private boolean createTopicIfNotExists(Set<String> topicsList, String topicName) { - - if (topicsList.contains(topicName)) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); - } - return true; - } - - CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(deConfiguration.getUebServers(), deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(), - deConfiguration.getCreateTopic().getReplicationCount()); - - CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus(); - if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); - } - } else if (status == CambriaOperationStatus.OK) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED); - } - } else { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED); - } - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); - - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); - - return false; - } - - return true; - } - - public static String buildTopicName(String topicName, String environment) { - return topicName + "-" + environment.toUpperCase(); - } - - public boolean isActive() { - return this.status.get(); - } - - public long getCurrentRetryInterval() { - return currentRetryInterval; - } - - protected void setCambriaHandler(CambriaHandler cambriaHandler) { - this.cambriaHandler = cambriaHandler; - } + public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine"; + public static final String ALREADY_EXISTS = "ALREADY_EXISTS"; + public static final String CONSUMER = "CONSUMER"; + public static final String PRODUCER = "PRODUCER"; + public static final String CREATED = "CREATED"; + public static final String FAILED = "FAILED"; + public static final Integer HTTP_OK = 200; + + private Long delayBeforeStartFlow = 0l; + private DistributionEngineConfiguration deConfiguration; + private String envName; + private long retryInterval; + private long currentRetryInterval; + private long maxInterval; + boolean maximumRetryInterval = false; + private AtomicBoolean status = null; + ComponentsUtils componentsUtils = null; + DistributionEnginePollingTask distributionEnginePollingTask = null; + private OperationalEnvironmentEntry environmentEntry; + + private CambriaHandler cambriaHandler = new CambriaHandler(); + + public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) { + super(); + this.delayBeforeStartFlow = delayBeforeStartFlow; + this.deConfiguration = deConfiguration; + this.envName = envName; + this.retryInterval = deConfiguration.getInitRetryIntervalSec(); + this.currentRetryInterval = retryInterval; + this.maxInterval = deConfiguration.getInitMaxIntervalSec(); + this.status = status; + this.componentsUtils = componentsUtils; + this.distributionEnginePollingTask = distributionEnginePollingTask; + this.environmentEntry = environmentEntry; + } + + private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); + + private static final Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class); + + ScheduledFuture<?> scheduledFuture = null; + + public void startTask() { + if (scheduledExecutorService != null) { + Integer retryInterval = deConfiguration.getInitRetryIntervalSec(); + logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow); + this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS); + + } + } + + public void restartTask() { + + this.stopTask(); + + logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval); + + long lastCurrentInterval = currentRetryInterval; + incrementRetryInterval(); + + this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS); + + } + + protected void incrementRetryInterval() { + if (currentRetryInterval < maxInterval) { + currentRetryInterval *= 2; + if (currentRetryInterval > maxInterval) { + setMaxRetryInterval(); + } + } else { + setMaxRetryInterval(); + } + } + + private void setMaxRetryInterval() { + currentRetryInterval = maxInterval; + maximumRetryInterval = true; + logger.debug("Set next retry init interval to {}", maxInterval); + } + + public void stopTask() { + if (scheduledFuture != null) { + boolean result = scheduledFuture.cancel(true); + logger.debug("Stop reinit task. result = {}", result); + if (false == result) { + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); + } + scheduledFuture = null; + } + } + + public void destroy() { + this.stopTask(); + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + } + } + + @Override + public void run() { + + boolean result = false; + result = initFlow(); + + if (true == result) { + this.stopTask(); + this.status.set(true); + if (this.distributionEnginePollingTask != null) { + String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName); + logger.debug("start polling distribution status topic {}", topicName); + this.distributionEnginePollingTask.startTask(topicName); + } + } else { + if (false == maximumRetryInterval) { + this.restartTask(); + } + } + } + + /** + * run initialization flow + * + * @return + */ + public boolean initFlow() { + + logger.trace("Start init flow for environment {}", this.envName); + + Set<String> topicsList = null; + Either<Set<String>, CambriaErrorResponse> getTopicsRes = null; + + getTopicsRes = cambriaHandler.getTopics(environmentEntry.getDmaapUebAddress().stream().collect(Collectors.toList())); + if (getTopicsRes.isRight()) { + CambriaErrorResponse status = getTopicsRes.right().value(); + if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) { + topicsList = new HashSet<>(); + } else { + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); + return false; + } + } else { + topicsList = getTopicsRes.left().value(); + } + + String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName); + logger.debug("Going to handle topic {}", notificationTopic); + + boolean status = createTopicIfNotExists(topicsList, notificationTopic); + if (false == status) { + return false; + } + + CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER); + + CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus(); + + if (createStatus != CambriaOperationStatus.OK) { + return false; + } + + String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName); + logger.debug("Going to handle topic {}", statusTopic); + status = createTopicIfNotExists(topicsList, statusTopic); + if (false == status) { + return false; + } + + CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER); + + if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) { + return false; + } + + return true; + } + + private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) { + CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), environmentEntry.getUebApikey(), subscriberType, topicName); + + String role = CONSUMER; + if (subscriberType == SubscriberTypeEnum.PRODUCER) { + role = PRODUCER; + } + auditRegistration(topicName, registerStatus, role); + return registerStatus; + } + + private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) { + if (componentsUtils != null) { + Integer httpCode = registerProducerStatus.getHttpCode(); + String httpCodeStr = String.valueOf(httpCode); + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, environmentEntry.getUebApikey(), httpCodeStr); + } + } + + private boolean createTopicIfNotExists(Set<String> topicsList, String topicName) { + + if (topicsList.contains(topicName)) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); + } + return true; + } + + CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(), + deConfiguration.getCreateTopic().getReplicationCount()); + + CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus(); + if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); + } + } else if (status == CambriaOperationStatus.OK) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED); + } + } else { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED); + } + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); + return false; + } + + return true; + } + + public static String buildTopicName(String topicName, String environment) { + return topicName + "-" + environment.toUpperCase(); + } + + public boolean isActive() { + return this.status.get(); + } + + public long getCurrentRetryInterval() { + return currentRetryInterval; + } + + protected void setCambriaHandler(CambriaHandler cambriaHandler) { + this.cambriaHandler = cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java index fc7c473d6b..b4f4863284 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java @@ -20,188 +20,189 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - +import com.att.nsa.cambria.client.CambriaConsumer; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; public class DistributionEnginePollingTask implements Runnable { - public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling"; - - private String topicName; - private ComponentsUtils componentUtils; - private int fetchTimeoutInSec = 15; - private int pollingIntervalInSec; - private String consumerId; - private String consumerGroup; - private DistributionEngineConfiguration distributionEngineConfiguration; - - private CambriaHandler cambriaHandler = new CambriaHandler(); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build()); - - private static Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class.getName()); - - ScheduledFuture<?> scheduledFuture = null; - private CambriaConsumer cambriaConsumer = null; - - private DistributionEngineClusterHealth distributionEngineClusterHealth = null; - - public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, String envName, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth) { - - this.componentUtils = componentUtils; - this.distributionEngineConfiguration = distributionEngineConfiguration; - DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic(); - this.pollingIntervalInSec = statusConfig.getPollingIntervalSec(); - this.fetchTimeoutInSec = statusConfig.getFetchTimeSec(); - this.consumerGroup = statusConfig.getConsumerGroup(); - this.consumerId = statusConfig.getConsumerId(); - this.distributionEngineClusterHealth = distributionEngineClusterHealth; - } - - public void startTask(String topicName) { - - this.topicName = topicName; - logger.debug("start task for polling topic {}", topicName); - if (fetchTimeoutInSec < 15) { - logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default"); - fetchTimeoutInSec = 15; - } - try { - cambriaConsumer = cambriaHandler.createConsumer(distributionEngineConfiguration.getUebServers(), topicName, distributionEngineConfiguration.getUebPublicKey(), distributionEngineConfiguration.getUebSecretKey(), consumerId, consumerGroup, - fetchTimeoutInSec * 1000); - - if (scheduledPollingService != null) { - logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec); - scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS); - - } - } catch (Exception e) { - logger.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); - } - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - logger.debug("Stop polling task. result = {}", result); - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); - } - scheduledFuture = null; - } - if (cambriaConsumer != null) { - logger.debug("close consumer"); - cambriaHandler.closeConsumer(cambriaConsumer); - } - - } - - public void destroy() { - this.stopTask(); - shutdownExecutor(); - } - - @Override - public void run() { - logger.trace("run() method. polling queue {}", topicName); - - try { - // init error - if (cambriaConsumer == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); - stopTask(); - return; - } - - Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer); - // fetch error - if (fetchResult.isRight()) { - CambriaErrorResponse errorResponse = fetchResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value()); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value()); - - // TODO: if status== internal error (connection problem) change - // state to inactive - // in next try, if succeed - change to active - return; - } - - // success - Iterable<String> messages = fetchResult.left().value(); - for (String message : messages) { - logger.trace("received message {}", message); - try { - DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class); - componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(), - String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason()); - - distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown(); - - } catch (Exception e) { - logger.debug("failed to convert message to object", e); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); - } - - } - } catch (Exception e) { - logger.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); - } - - } - - private void shutdownExecutor() { - if (scheduledPollingService == null) - return; - - scheduledPollingService.shutdown(); // Disable new tasks from being - // submitted - try { - // Wait a while for existing tasks to terminate - if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) { - scheduledPollingService.shutdownNow(); // Cancel currently - // executing tasks - // Wait a while for tasks to respond to being cancelled - if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) - logger.debug("Pool did not terminate"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - scheduledPollingService.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } + public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling"; + + private String topicName; + private ComponentsUtils componentUtils; + private int fetchTimeoutInSec = 15; + private int pollingIntervalInSec; + private String consumerId; + private String consumerGroup; + + private CambriaHandler cambriaHandler = new CambriaHandler(); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private DistributionCompleteReporter distributionCompleteReporter; + + private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build()); + + private static final Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class); + + ScheduledFuture<?> scheduledFuture = null; + private CambriaConsumer cambriaConsumer = null; + + private DistributionEngineClusterHealth distributionEngineClusterHealth = null; + + private OperationalEnvironmentEntry environmentEntry; + + public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) { + + this.componentUtils = componentUtils; + DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic(); + this.pollingIntervalInSec = statusConfig.getPollingIntervalSec(); + this.fetchTimeoutInSec = statusConfig.getFetchTimeSec(); + this.consumerGroup = statusConfig.getConsumerGroup(); + this.consumerId = statusConfig.getConsumerId(); + this.distributionEngineClusterHealth = distributionEngineClusterHealth; + this.environmentEntry = environmentEntry; + this.distributionCompleteReporter = distributionCompleteReporter; + } + + public void startTask(String topicName) { + + this.topicName = topicName; + logger.debug("start task for polling topic {}", topicName); + if (fetchTimeoutInSec < 15) { + logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default"); + fetchTimeoutInSec = 15; + } + try { + cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup, + fetchTimeoutInSec * 1000); + + if (scheduledPollingService != null) { + logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec); + scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS); + + } + } catch (Exception e) { + logger.debug("unexpected error occured", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + } + } + + public void stopTask() { + if (scheduledFuture != null) { + boolean result = scheduledFuture.cancel(true); + logger.debug("Stop polling task. result = {}", result); + if (false == result) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); + } + scheduledFuture = null; + } + if (cambriaConsumer != null) { + logger.debug("close consumer"); + cambriaHandler.closeConsumer(cambriaConsumer); + } + + } + + public void destroy() { + this.stopTask(); + shutdownExecutor(); + } + + @Override + public void run() { + logger.trace("run() method. polling queue {}", topicName); + + try { + // init error + if (cambriaConsumer == null) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); + stopTask(); + return; + } + + Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer); + // fetch error + if (fetchResult.isRight()) { + CambriaErrorResponse errorResponse = fetchResult.right().value(); + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse); + + // TODO: if status== internal error (connection problem) change + // state to inactive + // in next try, if succeed - change to active + return; + } + + // success + Iterable<String> messages = fetchResult.left().value(); + for (String message : messages) { + logger.trace("received message {}", message); + try { + DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class); + handleDistributionNotificationMsg(notification); + distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown(); + } catch (Exception e) { + logger.debug("failed to convert message to object", e); + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); + } + + } + } catch (Exception e) { + logger.debug("unexpected error occured", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + } + + } + + private void handleDistributionNotificationMsg(DistributionStatusNotification notification) { + componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(), + String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason()); + if (notification.isDistributionCompleteNotification()) { + distributionCompleteReporter.reportDistributionComplete(notification); + } + } + + private void shutdownExecutor() { + if (scheduledPollingService == null) + return; + + scheduledPollingService.shutdown(); // Disable new tasks from being + // submitted + try { + // Wait a while for existing tasks to terminate + if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) { + scheduledPollingService.shutdownNow(); // Cancel currently + // executing tasks + // Wait a while for tasks to respond to being cancelled + if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) + logger.debug("Pool did not terminate"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + scheduledPollingService.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java index 16a0a1dc31..62af4b8514 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java @@ -20,20 +20,13 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionException; - -import javax.annotation.PreDestroy; - import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -41,79 +34,83 @@ import org.springframework.stereotype.Component; @Component("distributionNotificationSender") public class DistributionNotificationSender { - protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending"; - - private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName()); - - // final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; - // final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL - // + "resources/%s/%s/artifacts/%s"; - // final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; - - @javax.annotation.Resource - InterfaceLifecycleOperation interfaceLifecycleOperation; - - @javax.annotation.Resource - protected ComponentsUtils componentUtils; - - ExecutorService executorService = null; - - CambriaHandler cambriaHandler = new CambriaHandler(); - - NotificationExecutorService notificationExecutorService = new NotificationExecutorService(); - - public DistributionNotificationSender() { - super(); - - DistributionNotificationTopicConfig distributionNotificationTopic = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic(); - - executorService = notificationExecutorService.createExcecutorService(distributionNotificationTopic); - } - - @PreDestroy - public void shutdown() { - logger.debug("Going to close notificationExecutorService"); - if (executorService != null) { - - long maxWaitingTime = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds(); - - notificationExecutorService.shutdownAndAwaitTermination(executorService, maxWaitingTime + 1); - } - } - - public StorageOperationStatus sendNotification(String topicName, String distributionId, DistributionEngineConfiguration deConfiguration, String envName, INotificationData notificationData, Service service, String userId, String modifierName) { - - Runnable task = new PublishNotificationRunnable(envName, distributionId, service, notificationData, deConfiguration, topicName, userId, modifierName, cambriaHandler, componentUtils, ThreadLocalsHolder.getUuid()); - try { - executorService.submit(task); - } catch (RejectedExecutionException e) { - logger.warn("Failed to submit task. Number of threads exceeeds", e); - return StorageOperationStatus.OVERLOAD; - } - - return StorageOperationStatus.OK; - } - - /** - * Audit the publishing notification in case of internal server error. - * - * @param topicName - * @param status - * @param distributionId - * @param envName - */ - private void auditDistributionNotificationInternalServerError(String topicName, StorageOperationStatus status, String distributionId, String envName) { - - if (this.componentUtils != null) { - this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, "", " ", "Service", " ", " ", " ", envName, " ", topicName, distributionId, "Error: Internal Server Error. " + status, " "); - } - } - - protected CambriaErrorResponse publishNotification(INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName) { - - CambriaErrorResponse status = cambriaHandler.sendNotification(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data); + protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending"; + + private static final Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class); + + @javax.annotation.Resource + protected ComponentsUtils componentUtils; + private CambriaHandler cambriaHandler = new CambriaHandler(); + private DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + public ActionStatus sendNotification(String topicName, String distributionId, EnvironmentMessageBusData messageBusData, INotificationData notificationData, Service service, String userId, String modifierName) { + long startTime = System.currentTimeMillis(); + CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, messageBusData.getUebPublicKey(), messageBusData.getUebPrivateKey(), messageBusData.getDmaaPuebEndpoints(), notificationData, + deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds()); + logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode()); + auditDistributionNotification(topicName, distributionId, status, service, messageBusData.getEnvId(), userId, modifierName, notificationData.getWorkloadContext(), messageBusData.getTenant()); + long endTime = System.currentTimeMillis(); + logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime)); + return convertCambriaResponse(status); + } + + private void auditDistributionNotification(String topicName, String distributionId, CambriaErrorResponse status, Service service, String envId, String userId, String modifierName, String workloadContext, String tenant) { + if (this.componentUtils != null) { + Integer httpCode = status.getHttpCode(); + String httpCodeStr = String.valueOf(httpCode); + + String desc = getDescriptionFromErrorResponse(status); + + this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envId, service.getLifecycleState().name(), topicName, + distributionId, desc, httpCodeStr, workloadContext, tenant); + } + } + + private String getDescriptionFromErrorResponse(CambriaErrorResponse status) { + + CambriaOperationStatus operationStatus = status.getOperationStatus(); + + switch (operationStatus) { + case OK: + return "OK"; + case AUTHENTICATION_ERROR: + return "Error: Authentication problem towards U-EB server"; + case INTERNAL_SERVER_ERROR: + return "Error: Internal U-EB server error"; + case UNKNOWN_HOST_ERROR: + return "Error: Cannot reach U-EB server host"; + case CONNNECTION_ERROR: + return "Error: Cannot connect to U-EB server"; + case OBJECT_NOT_FOUND: + return "Error: object not found in U-EB server"; + default: + return "Error: Internal Cambria server problem"; + + } + + } + + private ActionStatus convertCambriaResponse(CambriaErrorResponse status) { + CambriaOperationStatus operationStatus = status.getOperationStatus(); + + switch (operationStatus) { + case OK: + return ActionStatus.OK; + case AUTHENTICATION_ERROR: + return ActionStatus.AUTHENTICATION_ERROR; + case INTERNAL_SERVER_ERROR: + return ActionStatus.GENERAL_ERROR; + case UNKNOWN_HOST_ERROR: + return ActionStatus.UNKNOWN_HOST; + case CONNNECTION_ERROR: + return ActionStatus.CONNNECTION_ERROR; + case OBJECT_NOT_FOUND: + return ActionStatus.OBJECT_NOT_FOUND; + default: + return ActionStatus.GENERAL_ERROR; + + } + } - return status; - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java index 73a0336361..006aa26082 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java @@ -22,63 +22,67 @@ package org.openecomp.sdc.be.components.distribution.engine; public class DistributionStatusNotification { - String distributionID; - String consumerID; - long timestamp; - String artifactURL; - DistributionStatusNotificationEnum status; - String errorReason; - - public String getDistributionID() { - return distributionID; - } - - public void setDistributionID(String distributionId) { - this.distributionID = distributionId; - } - - public String getConsumerID() { - return consumerID; - } - - public void setConsumerID(String consumerId) { - this.consumerID = consumerId; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public DistributionStatusNotificationEnum getStatus() { - return status; - } - - public void setStatus(DistributionStatusNotificationEnum status) { - this.status = status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } - - @Override - public String toString() { - return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; - } + String distributionID; + String consumerID; + long timestamp; + String artifactURL; + DistributionStatusNotificationEnum status; + String errorReason; + + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionId) { + this.distributionID = distributionId; + } + + public String getConsumerID() { + return consumerID; + } + + public void setConsumerID(String consumerId) { + this.consumerID = consumerId; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public DistributionStatusNotificationEnum getStatus() { + return status; + } + + public void setStatus(DistributionStatusNotificationEnum status) { + this.status = status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } + + public boolean isDistributionCompleteNotification() { + return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK.equals(status) || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR.equals(status); + } + + @Override + public String toString() { + return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java index bd77f3915a..65aa18ee97 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine; public enum DistributionStatusNotificationEnum { - DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED + DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED, COMPONENT_DONE_ERROR, COMPONENT_DONE_OK, DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java new file mode 100644 index 0000000000..3d35a84d7a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import fj.data.Either; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.security.SecurityUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; + +/** + * Allows to create DMAAP client of type MRConsumer according received configuration parameters + */ +@Component("dmaapClientFactory") +public class DmaapClientFactory { + private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class); + + /** + * Creates DMAAP consumer according to received parameters + * @param parameters + * @return an instance object of type MRConsumer + * @throws IOException + */ + public MRConsumer create(DmaapConsumerConfiguration parameters) throws Exception { + MRConsumer consumer = MRClientFactory.createConsumer(buildProperties(parameters)); + logger.info("MRConsumer created for topic {}", parameters.getTopic()); + return consumer; + } + + private Properties buildProperties(DmaapConsumerConfiguration parameters) throws Exception{ + Properties props = new Properties(); + Either<String,String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() ); + if (passkey.isRight()){ + throw new GeneralSecurityException("invalid password, cannot build properties"); + } + props.setProperty("Latitude", Double.toString(parameters.getLatitude())); + props.setProperty("Longitude", Double.toString(parameters.getLongitude())); + props.setProperty("Version", parameters.getVersion()); + props.setProperty("ServiceName", parameters.getServiceName()); + props.setProperty("Environment", parameters.getEnvironment()); + props.setProperty("Partner", parameters.getPartner()); + props.setProperty("routeOffer", parameters.getRouteOffer()); + props.setProperty("Protocol", parameters.getProtocol()); + props.setProperty("username", parameters.getCredential().getUsername()); + props.setProperty("password", passkey.left().value() ); + props.setProperty("contenttype", parameters.getContenttype()); + props.setProperty("host", parameters.getHosts()); + props.setProperty("topic", parameters.getTopic()); + props.setProperty("group", parameters.getConsumerGroup()); + props.setProperty("id", parameters.getConsumerId()); + props.setProperty("timeout", Integer.toString(parameters.getTimeoutMs())); + props.setProperty("limit", Integer.toString(parameters.getLimit())); + props.setProperty("AFT_DME2_REQ_TRACE_ON", Boolean.toString(parameters.isDme2TraceOn())); + props.setProperty("AFT_ENVIRONMENT", parameters.getAftEnvironment()); + props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs())); + props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs())); + props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs())); + + String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath(); + ensureFileExists(dme2PreferredRouterFilePath); + props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath); + + props.setProperty("TransportType", "DME2"); + props.setProperty("SubContextPath", "/"); + props.setProperty("MethodType", "GET"); + props.setProperty("authKey", ""); + props.setProperty("authDate", ""); + props.setProperty("filter", ""); + props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", ""); + props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", ""); + props.setProperty("sessionstickinessrequired", "no"); + + return props; + } + + private void ensureFileExists(String filePath) throws IOException { + File file = new File(filePath); + if(file.createNewFile()) { + logger.info("The file {} has been created on the disk", file.getAbsolutePath()); + } + else{ + logger.info("The file {} already exists", file.getAbsolutePath()); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java new file mode 100644 index 0000000000..e0661f4b22 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRConsumer; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * Allows consuming DMAAP topic according to received consumer parameters + * Allows processing received messages. + */ +@Service +public class DmaapConsumer { + private final ExecutorFactory executorFactory; + private final DmaapClientFactory dmaapClientFactory; + private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class); + + @Autowired + private DmaapHealth dmaapHealth; + /** + * Allows to create an object of type DmaapConsumer + * @param executorFactory + * @param dmaapClientFactory + */ + @Autowired + public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory) { + this.executorFactory = executorFactory; + this.dmaapClientFactory = dmaapClientFactory; + } + + /** + * Allows consuming DMAAP topic according to received consumer parameters + * @param notificationReceived + * @param exceptionHandler + * @throws Exception + */ + public void consumeDmaapTopic(Consumer<String> notificationReceived, UncaughtExceptionHandler exceptionHandler) throws Exception { + + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); + String topic = dmaapConsumerParams.getTopic(); + logger.info("Starting to consume topic {} for DMAAP consumer with the next parameters {}. ", topic, dmaapConsumerParams); + MRConsumer consumer = dmaapClientFactory.create(dmaapConsumerParams); + ScheduledExecutorService pollExecutor = executorFactory.createScheduled(topic + "Client"); + ExecutorService notificationExecutor = executorFactory.create(topic + "Consumer", exceptionHandler); + + pollExecutor.scheduleWithFixedDelay(() -> { + logger.info("Trying to fetch messages from topic: {}", topic); + boolean isTopicAvailable = false; + try { + Iterable<String> messages = consumer.fetch(); + isTopicAvailable = true ; + if (messages != null) { + for (String msg : messages) { + logger.info("The DMAAP message {} received. The topic is {}.", msg, topic); + notificationExecutor.execute(() -> notificationReceived.accept(msg)); + } + } + //successfully fetched + } + catch (Exception e) { + logger.error("The exception {} occured upon fetching DMAAP message", e); + } + dmaapHealth.report( isTopicAvailable ); + }, 0L, dmaapConsumerParams.getPollingInterval(), TimeUnit.SECONDS); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java new file mode 100644 index 0000000000..ba5e9f7c9c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java @@ -0,0 +1,220 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.commons.validator.routines.UrlValidator; +import org.apache.http.client.utils.URIUtils; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.apache.commons.lang3.StringUtils.*; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE; + +@Component("dmaapHealth") +public class DmaapHealth { + + + protected static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaap.healthcheck"; + private static final String DMAAP_HEALTH_CHECK_STR = "dmaapHealthCheck"; + private static final Logger log = LoggerFactory.getLogger(DmaapHealth.class); + private static final Logger logHealth = LoggerFactory.getLogger(DMAAP_HEALTH_LOG_CONTEXT); + private HealthCheckInfo healthCheckInfo = DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + private long healthCheckReadTimeout = 20; + private long reconnectInterval = 5; + private HealthCheckScheduledTask healthCheckScheduledTask = null ; + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private ScheduledFuture<?> scheduledFuture = null; + private DmaapConsumerConfiguration configuration = null ; + + private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false); + private volatile AtomicBoolean reportedHealthState = null; + + public enum HealthCheckInfoResult { + OK(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())), + DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription())); + + private HealthCheckInfo healthCheckInfo; + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + + public enum DmaapStatusDescription { + OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong "); + + private String desc; + DmaapStatusDescription(String desc) { + this.desc = desc; + } + public String getDescription() { + return desc; + } + + } + + @PostConstruct + public DmaapHealth init() { + log.trace("Enter init method of Dmaap health"); + synchronized (DmaapHealth.class){ + this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); + + Integer pollingInterval = configuration.getPollingInterval(); + if (pollingInterval != null && pollingInterval!=0) { + reconnectInterval = pollingInterval; + } + Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs(); + if (healthCheckReadTimeoutConfig != null) { + this.healthCheckReadTimeout = healthCheckReadTimeoutConfig; + } + this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other + startHealthCheckTask(true); + } + log.trace("Exit init method of DistributionEngineClusterHealth"); + return this; + } + + @PreDestroy + protected void destroy() { + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + if (scheduler != null) { + scheduler.shutdown(); + } + } + + /** + * Start health check task. + * + * @param startTask + */ + public void startHealthCheckTask( boolean startTask ) { + synchronized (DmaapHealth.class){ + if (startTask && this.scheduledFuture == null) { + this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS); + } + } + } + + public void report(Boolean isUp){ + if (reportedHealthState == null) + reportedHealthState = new AtomicBoolean(isUp); + reportedHealthState.set(isUp); + } + + public void logAlarm(boolean lastHealthState) { + try{ + if ( lastHealthState ) { + BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR ); + } else { + BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR ); + } + }catch( Exception e ){ + log.debug("cannot logAlarm -> {}" ,e ); + } + } + + public DmaapConsumerConfiguration getConfiguration() { + return configuration; + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + + /** + * Health Check Task Scheduler - infinite check. + */ + public class HealthCheckScheduledTask implements Runnable { + private final DmaapConsumerConfiguration config; + private static final int timeout = 8192; + + public HealthCheckScheduledTask(final DmaapConsumerConfiguration config){ + this.config = config; + } + @Override + public void run() { + logHealth.trace("Executing Dmaap Health Check Task - Start"); + boolean prevIsReachable = false; + boolean reachable = false; + //first try simple ping + try{ + if ( reportedHealthState != null ){ + reachable = reportedHealthState.get(); + } + else{ + reachable = false; + } + prevIsReachable = lastHealthState.getAndSet( reachable ); + healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo; + } + catch( Exception e ){ + log.debug("{} | cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e ); + prevIsReachable = lastHealthState.getAndSet(false); + healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo; + } + if (prevIsReachable != lastHealthState.get()) + logAlarm( lastHealthState.get() ); + } + + + /** + * @deprecated (health is reported outside from EnvironmentEngine consumer fetch) + */ + @Deprecated + public boolean isICMPReachable( ) throws IOException{ + try{ + String hostname = getUrlHost(config.getHosts()); + return InetAddress.getByName( hostname ).isReachable(timeout); + }catch( URISyntaxException e ){ + log.debug("{} | malformed host configuration -> ",DMAAP_HEALTH_CHECK_STR , e); + } + return false; + } + } + + public static String getUrlHost(String qualifiedHost) throws URISyntaxException{ + //region - parse complex format ex. <http://URL:PORT> + try{ + UrlValidator validator = new UrlValidator(); + if (validator.isValid(qualifiedHost)){ + return URIUtils.extractHost(new URI(qualifiedHost)).getHostName(); + }else{ + log.debug("{} | invalid url format, continuing ", DMAAP_HEALTH_CHECK_STR ); + } + }catch(URISyntaxException e){ + log.debug("{} | invalid url format, continuing {} ", DMAAP_HEALTH_CHECK_STR , e); + } + //endregion + + //region - try shortcut format <URL> or <URL:PORT> + if ( countMatches( qualifiedHost , ":") <= 1){ + String[] address = qualifiedHost.split(":"); + if ( address.length>0 && isNotBlank(address[0]) ){ + return address[0]; + } + } + //endregion + throw new URISyntaxException( qualifiedHost , "invalid hostname, expecting a single <host:port> , (valid ex. www.google.com:80 | www.google.com | http:\\\\www.google.com:8181)"); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java new file mode 100644 index 0000000000..3f86fe73de --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +/* Example { + "operationalEnvironmentId": "28122015552391", + "operationalEnvironmentName": "Operational Environment Name", + "operationalEnvironmentType": "ECOMP", + "tenantContext": "TEST", + "workloadContext": "ECOMP_E2E-IST", + "action": "Create" + }*/ +public class DmaapNotificationDataImpl implements IDmaapNotificationData, IDmaapAuditNotificationData { + + private String operationalEnvironmentId; + private String operationalEnvironmentType; + private String action; + private String operationalEnvironmentName; + private String tenantContext; + + @Override + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + @Override + public OperationaEnvironmentTypeEnum getOperationalEnvironmentType() { + return OperationaEnvironmentTypeEnum.findByName(operationalEnvironmentType); + } + + @Override + public DmaapActionEnum getAction() { + return DmaapActionEnum.findByName(action); + } + + @Override + public String getOperationalEnvironmentName() { + return operationalEnvironmentName; + } + + @Override + public String getTenantContext() { + return tenantContext; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java new file mode 100644 index 0000000000..67977b6361 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.ArrayList; +import java.util.List; + +/** + * a pojo which holds all the necessary data to communicate with the message bus + * this class is a reflection ot the {@link OperationalEnvironmentEntry} class + */ +public class EnvironmentMessageBusData { + + private List<String> dmaaPuebEndpoints; + + private String uebPublicKey; + + private String uebPrivateKey; + + private String envId; + + private String tenant; + + public EnvironmentMessageBusData() { + } + + public EnvironmentMessageBusData(OperationalEnvironmentEntry operationalEnvironment) { + this.dmaaPuebEndpoints = new ArrayList<>(operationalEnvironment.getDmaapUebAddress()); + this.uebPublicKey = operationalEnvironment.getUebApikey(); + this.uebPrivateKey = operationalEnvironment.getUebSecretKey(); + this.envId = operationalEnvironment.getEnvironmentId(); + this.tenant = operationalEnvironment.getTenant(); + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public List<String> getDmaaPuebEndpoints() { + return dmaaPuebEndpoints; + } + + public void setDmaaPuebEndpoints(List<String> dmaaPuebEndpoints) { + this.dmaaPuebEndpoints = dmaaPuebEndpoints; + } + + public String getUebPublicKey() { + return uebPublicKey; + } + + public void setUebPublicKey(String uebPublicKey) { + this.uebPublicKey = uebPublicKey; + } + + public String getUebPrivateKey() { + return uebPrivateKey; + } + + public void setUebPrivateKey(String uebPrivateKey) { + this.uebPrivateKey = uebPrivateKey; + } + + public String getEnvId() { + return envId; + } + + public void setEnvId(String envId) { + this.envId = envId; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java new file mode 100644 index 0000000000..822464c631 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java @@ -0,0 +1,526 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.aft.dme2.iterator.domain.DME2EndpointReference; +import com.att.aft.dme2.manager.registry.DME2Endpoint; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.DmaapActionEnum; +import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.OperationaEnvironmentTypeEnum; +import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.be.config.DmeConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut; + +/** + * Allows to consume DMAAP topic and handle received notifications + */ +@Service +public class EnvironmentsEngine implements INotificationHandler { + + private static final String MESSAGE_BUS = "MessageBus"; + private static final String UNKNOWN = "Unknown"; + private static final Logger log = LoggerFactory.getLogger(EnvironmentsEngine.class); + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); + + private Map<String, OperationalEnvironmentEntry> environments; + private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>(); + private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>(); + private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>(); + + private final DmaapConsumer dmaapConsumer; + private final OperationalEnvironmentDao operationalEnvironmentDao; + private final DME2EndpointIteratorCreator epIterCreator; + private final AaiRequestHandler aaiRequestHandler; + private final ComponentsUtils componentUtils; + private final CambriaHandler cambriaHandler; + private final DistributionEngineClusterHealth distributionEngineClusterHealth; + private final DistributionCompleteReporter distributionCompleteReporter; + + public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao, DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils, CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth, DistributionCompleteReporter distributionCompleteReporter) { + this.dmaapConsumer = dmaapConsumer; + this.operationalEnvironmentDao = operationalEnvironmentDao; + this.epIterCreator = epIterCreator; + this.aaiRequestHandler = aaiRequestHandler; + this.componentUtils = componentUtils; + this.cambriaHandler = cambriaHandler; + this.distributionEngineClusterHealth = distributionEngineClusterHealth; + this.distributionCompleteReporter = distributionCompleteReporter; + } + + @VisibleForTesting + @PostConstruct + void init() { + log.trace("Environments engine has been initialized. "); + try { + environments = populateEnvironments(); + createUebTopicsForEnvironments(); + dmaapConsumer.consumeDmaapTopic(this::handleMessage, + (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e)); + } + catch (Exception e) { + log.error("An error occurred upon consuming topic by Dmaap consumer client." , e); + } + } + public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry, + AtomicBoolean status, + Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask){ + connectUebTopic(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask); + + } + + public void connectUebTopicForDistributionConfTopic(String envName, + AtomicBoolean status, + Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask){ + connectUebTopic(environments.get(envName), status, envNamePerInitTask, envNamePerPollingTask); + + } + /** + * Allows to create and run UEB initializing and polling tasks + * @param status + * @param envNamePerInitTask + * @param envNamePerPollingTask + * @param opEnvEntry + */ + private void connectUebTopic(OperationalEnvironmentEntry opEnvEntry, AtomicBoolean status, + Map<String, DistributionEngineInitTask> envNamePerInitTask, + Map<String, DistributionEnginePollingTask> envNamePerPollingTask) { + + String envId = opEnvEntry.getEnvironmentId(); + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask( + distributionEngineConfiguration, distributionCompleteReporter, componentUtils, distributionEngineClusterHealth, + opEnvEntry); + String envName = configurationManager.getDistributionEngineConfiguration().getEnvironments().get(0); + DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, + distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask, + opEnvEntry); + distributionEngineInitTask.startTask(); + envNamePerInitTask.put(envId, distributionEngineInitTask); + envNamePerPollingTask.put(envId, distributionEnginePollingTask); + + log.debug("Environment envId = {} has been connected to the UEB topic", envId); + } + + @Override + public boolean handleMessage(String notification) { + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager() + .getConfiguration().getDmaapConsumerConfiguration(); + Supplier<Boolean> supplier = () -> handleMessageLogic(notification); + Either<Boolean, Boolean> eitherTimeOut = runMethodWithTimeOut(supplier, + dmaapConsumerParams.getTimeLimitForNotificationHandleMs()); + + boolean result; + if (eitherTimeOut.isRight()) { + result = false; + } else { + result = eitherTimeOut.left().value(); + } + return result; + } + + public boolean handleMessageLogic(String notification) { + Wrapper<Boolean> errorWrapper = new Wrapper<>(); + Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper = new Wrapper<>(); + try { + + log.debug("handle message - for operational environment notification received: {}", notification); + Gson gsonObj = new GsonBuilder().create(); + + IDmaapNotificationData notificationData = gsonObj.fromJson(notification, + DmaapNotificationDataImpl.class); + IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification, + DmaapNotificationDataImpl.class); + + AuditingActionEnum actionEnum; + switch(notificationData.getAction()) { + case CREATE: + actionEnum = AuditingActionEnum.CREATE_ENVIRONMENT; + break; + case UPDATE: + actionEnum = AuditingActionEnum.UPDATE_ENVIRONMENT; + break; + case DELETE: + actionEnum = AuditingActionEnum.DELETE_ENVIRONMENT; + break; + default: + actionEnum = AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION; + break; + } + componentUtils.auditEnvironmentEngine(actionEnum, + notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(), + notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(), + auditNotificationData.getTenantContext()); + + if (errorWrapper.isEmpty()) { + validateNotification(errorWrapper, notificationData, auditNotificationData); + } + // Perform Save In-Progress Dao + if (errorWrapper.isEmpty()) { + saveEntryWithInProgressStatus(errorWrapper, opEnvEntryWrapper, notificationData); + } + + if (errorWrapper.isEmpty()) { + buildOpEnv(errorWrapper, opEnvEntryWrapper.getInnerElement()); + } + + } catch (Exception e) { + log.debug("handle message for operational environmet failed for notification: {} with error :{}", + notification, e.getMessage(), e); + errorWrapper.setInnerElement(false); + + } + return errorWrapper.isEmpty(); + } + + private void validateNotification(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData, + IDmaapAuditNotificationData auditNotificationData) { + // Check OperationaEnvironmentType + if (errorWrapper.isEmpty()) { + validateEnvironmentType(errorWrapper, notificationData, auditNotificationData); + } + // Check Action Type + if (errorWrapper.isEmpty()) { + validateActionType(errorWrapper, notificationData); + } + // Check is valid for create/update (not In-Progress state) + if (errorWrapper.isEmpty()) { + validateState(errorWrapper, notificationData); + } + } + + public void buildOpEnv(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + // Get Env Info From A&AI + if (errorWrapper.isEmpty()) { + retrieveOpEnvInfoFromAAI(errorWrapper, opEnvEntry); + } + + if (errorWrapper.isEmpty()) { + // Get List Of UEB Addresses From AFT_DME + retrieveUebAddressesFromAftDme(errorWrapper, opEnvEntry); + } + + // Create UEB keys and set them on EnvEntry + if (errorWrapper.isEmpty()) { + createUebKeys(errorWrapper, opEnvEntry); + } + + // Create Topics + if (errorWrapper.isEmpty()) { + log.debug("handle message - Create Topics"); + createUebTopicsForEnvironment(opEnvEntry); + } + + // Save Status Complete and Add to Map + if (errorWrapper.isEmpty()) { + saveEntryWithCompleteStatus(errorWrapper, opEnvEntry); + } + + // Update Environments Map + if (errorWrapper.isEmpty()) { + environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry); + } + else{ + saveEntryWithFailedStatus(errorWrapper, opEnvEntry); + } + } + + private void saveEntryWithFailedStatus(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - save OperationalEnvironment Failed Status"); + opEnvEntry.setStatus(EnvironmentStatusEnum.FAILED); + saveOpEnvEntry(errorWrapper, opEnvEntry); + } + + void saveEntryWithCompleteStatus(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - save OperationalEnvironment Complete Dao"); + opEnvEntry.setStatus(EnvironmentStatusEnum.COMPLETED); + saveOpEnvEntry(errorWrapper, opEnvEntry); + + } + + void retrieveUebAddressesFromAftDme(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Get List Of UEB Addresses From AFT_DME"); + try { + boolean isKeyFieldsValid = !isEmpty(opEnvEntry.getTenant()) && !isEmpty(opEnvEntry.getEcompWorkloadContext()); + if( isKeyFieldsValid ){ + String opEnvKey = map2OpEnvKey(opEnvEntry); + String environmentId = opEnvEntry.getEnvironmentId(); + List<String> uebHosts = discoverUebHosts(opEnvKey, environmentId); + opEnvEntry.setDmaapUebAddress(uebHosts.stream().collect(Collectors.toSet())); + } + else{ + errorWrapper.setInnerElement(false); + log.debug("Can Not Build AFT DME Key from workLoad & Tenant Fields."); + } + + } catch (DME2Exception e) { + errorWrapper.setInnerElement(false); + log.error("Failed to retrieve Ueb Addresses From DME. ", e); + } + } + + void createUebKeys(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Create UEB keys"); + List<String> discoverEndPoints = opEnvEntry.getDmaapUebAddress().stream() + .collect(Collectors.toList()); + Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = cambriaHandler + .createUebKeys(discoverEndPoints); + if (eitherCreateUebKeys.isRight()) { + errorWrapper.setInnerElement(false); + log.debug("handle message - failed to create UEB Keys"); + } else { + ApiCredential apiCredential = eitherCreateUebKeys.left().value(); + opEnvEntry.setUebApikey(apiCredential.getApiKey()); + opEnvEntry.setUebSecretKey(apiCredential.getApiSecret()); + } + } + + void retrieveOpEnvInfoFromAAI(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Get Env Info From A&AI"); + Either<OperationalEnvInfo, Integer> eitherOperationalEnvInfo = getOperationalEnvById( + opEnvEntry.getEnvironmentId()); + if (eitherOperationalEnvInfo.isRight()) { + errorWrapper.setInnerElement(false); + log.debug("handle message - failed to retrieve details from A&AI"); + } else { + OperationalEnvInfo operationalEnvInfo = eitherOperationalEnvInfo.left().value(); + opEnvEntry.setEcompWorkloadContext(operationalEnvInfo.getWorkloadContext()); + opEnvEntry.setTenant(operationalEnvInfo.getTenantContext()); + } + } + + void saveEntryWithInProgressStatus(Wrapper<Boolean> errorWrapper, Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - save OperationalEnvironment In-Progress Dao"); + OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry(); + // Entry Environment ID holds actually the environment NAME + opEnvEntry.setEnvironmentId(notificationData.getOperationalEnvironmentId()); + opEnvEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS); + opEnvEntry.setIsProduction(false); + saveOpEnvEntry(errorWrapper, opEnvEntry); + opEnvEntryWrapper.setInnerElement(opEnvEntry); + + } + + + void validateState(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - verify OperationalEnvironment not In-Progress"); + String opEnvId = notificationData.getOperationalEnvironmentId(); + + Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherOpEnv = operationalEnvironmentDao + .get(opEnvId); + if (eitherOpEnv.isLeft()) { + final OperationalEnvironmentEntry opEnvEntry = eitherOpEnv.left().value(); + if (StringUtils.equals(opEnvEntry.getStatus(), EnvironmentStatusEnum.IN_PROGRESS.getName())) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate State Failed Record Found With Status : {} Flow Stopped!", opEnvEntry.getStatus()); + } + } else { + CassandraOperationStatus operationStatus = eitherOpEnv.right().value(); + if (operationStatus != CassandraOperationStatus.NOT_FOUND) { + errorWrapper.setInnerElement(false); + log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId, + operationStatus); + } + } + + } + + void validateActionType(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - verify Action Type"); + DmaapActionEnum action = notificationData.getAction(); + if (action == DmaapActionEnum.DELETE) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate Action Type Failed With Action Type: {} Flow Stopped!", action); + } + } + + void validateEnvironmentType(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData, + IDmaapAuditNotificationData auditNotificationData) { + log.debug("handle message - verify OperationaEnvironmentType"); + OperationaEnvironmentTypeEnum envType = notificationData.getOperationalEnvironmentType(); + if (envType != OperationaEnvironmentTypeEnum.ECOMP) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate Environment Type Failed With Environment Type: {} Flow Stopped!", envType); + componentUtils.auditEnvironmentEngine(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE, + notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(), + notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(), + auditNotificationData.getTenantContext()); + } + } + + + private void saveOpEnvEntry(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry entry) { + entry.setLastModified(new Date(System.currentTimeMillis())); + CassandraOperationStatus saveStaus = operationalEnvironmentDao.save(entry); + if (saveStaus != CassandraOperationStatus.OK) { + errorWrapper.setInnerElement(false); + log.debug("handle message saving operational environmet failed for id :{} with error : {}", + entry.getEnvironmentId(), saveStaus); + } + } + + public List<String> discoverUebHosts(String opEnvKey, String env) throws DME2Exception { + DmeConfiguration dmeConfiguration = configurationManager.getConfiguration().getDmeConfiguration(); + List<String> uebHosts = new LinkedList<>(); + + String lookupURI = String.format("http://%s/service=%s/version=1.0.0/envContext=%s/partner=*", dmeConfiguration.getDme2Search(), opEnvKey, + env); + DME2EndpointIterator iterator = epIterCreator.create(lookupURI); + + // Beginning iteration + while (iterator.hasNext()) { + DME2EndpointReference ref = iterator.next(); + DME2Endpoint dmeEndpoint = ref.getEndpoint(); + log.debug("DME returns EP with UEB host {}, UEB port: {}", dmeEndpoint.getHost(), dmeEndpoint.getPort()); + uebHosts.add(dmeEndpoint.getHost()); + } + + return uebHosts; + } + + private String map2OpEnvKey(OperationalEnvironmentEntry entry) { + return String.format("%s.%s.%s", entry.getTenant(), entry.getEcompWorkloadContext(), MESSAGE_BUS); + } + + private Map<String, OperationalEnvironmentEntry> populateEnvironments() { + Map<String, OperationalEnvironmentEntry> envs = getEnvironmentsFromDb(); + OperationalEnvironmentEntry confEntry = readEnvFromConfig(); + envs.put(confEntry.getEnvironmentId(), confEntry); + return envs; + } + + private OperationalEnvironmentEntry readEnvFromConfig() { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + DistributionEngineConfiguration distributionEngineConfiguration = configurationManager + .getDistributionEngineConfiguration(); + entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey()); + entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey()); + + Set<String> puebEndpoints = new HashSet<>(); + puebEndpoints.addAll(distributionEngineConfiguration.getUebServers()); + entry.setDmaapUebAddress(puebEndpoints); + + String envName = distributionEngineConfiguration.getEnvironments().size() == 1 + ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN; + entry.setEnvironmentId(envName); + + if(log.isDebugEnabled()) { + log.debug("Enviroment read from configuration: {}", entry.toString()); + } + + return entry; + } + + private Map<String, OperationalEnvironmentEntry> getEnvironmentsFromDb() { + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> opEnvResult = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); + + if (opEnvResult.isLeft()) { + Map<String, OperationalEnvironmentEntry> resultMap = opEnvResult.left().value().stream() + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + resultMap.forEach( (key, value) -> log.debug("Enviroment loaded from DB: {}", value.toString()) ); + return resultMap; + } else { + CassandraOperationStatus status = opEnvResult.right().value(); + log.debug("Failed to populate Operation Envirenments Map from Cassandra, DB status: {}", status); + return new HashMap<>(); + } + } + + void createUebTopicsForEnvironments() { + environments.values().forEach(this::createUebTopicsForEnvironment); + } + + public void createUebTopicsForEnvironment(OperationalEnvironmentEntry opEnvEntry) { + String envId = opEnvEntry.getEnvironmentId(); + log.debug("Create Environment {} on UEB Topic.", envId); + AtomicBoolean status = new AtomicBoolean(false); + envNamePerStatus.put(envId, status); + + connectUebTopicTenantIsolation(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask); + } + + @VisibleForTesting + void setConfigurationManager(ConfigurationManager configurationManager) { + this.configurationManager = configurationManager; + } + + public Map<String, OperationalEnvironmentEntry> getEnvironments() { + return environments; + } + + + public Either<OperationalEnvInfo, Integer> getOperationalEnvById(String id) { + HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id); + if (resp.getStatusCode() == HttpStatus.SC_OK) { + try { + OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(resp.getResponse()); + + log.debug("Get \"{}\" operational environment. {}", id, operationalEnvInfo); + return Either.left(operationalEnvInfo); + } catch (Exception e) { + log.debug("Json convert to OperationalEnvInfo failed with exception ", e); + return Either.right(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } else { + log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id, + resp.getStatusCode(), resp.getDescription()); + return Either.right(resp.getStatusCode()); + } + } + + public OperationalEnvironmentEntry getEnvironmentById (String envId) { + return environments.get(envId); + } + + public boolean isInMap(OperationalEnvironmentEntry env) { + return isInMap(env.getEnvironmentId()); + } + + public boolean isInMap(String envId) { + return environments.containsKey(envId); + } + + public void addToMap(OperationalEnvironmentEntry opEnvEntry) { + environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry); + + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java new file mode 100644 index 0000000000..29579c64b7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +@Component("executorFactory") +/** + * Allows to create next kinds of single thread executors: SingleThreadExecutor and SingleThreadScheduledExecutor + */ +public class ExecutorFactory { + + private static final Logger logger = LoggerFactory.getLogger(EnvironmentsEngine.class); + + public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler){ + logger.info("Going to create single thread executor. "); + ThreadFactory threadFactory = createThreadFactory(name, exceptionHandler); + return Executors.newSingleThreadExecutor(threadFactory); + } + + public ScheduledExecutorService createScheduled(String name){ + logger.info("Going to create single thread scheduled executor. "); + ThreadFactory threadFactory = createThreadFactory(name, + (t, e) -> LoggerFactory.getLogger(UncaughtExceptionHandler.class).error("An error occurred: ", e)); + return Executors.newSingleThreadScheduledExecutor(threadFactory); + } + + private ThreadFactory createThreadFactory(String name, UncaughtExceptionHandler exceptionHandler) { + String nameFormat = name + "-%d"; + return new ThreadFactoryBuilder() + .setThreadFactory(Executors.defaultThreadFactory()) + .setNameFormat(nameFormat) + .setUncaughtExceptionHandler(exceptionHandler) + .setDaemon(true) + .build(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java index 169f4f3efa..4a917710a9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java @@ -24,40 +24,40 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; public interface IArtifactInfo { - /** Artifact File name */ - String getArtifactName(); - - /** - * Artifact Type.<br> - * Following are valid values : HEAT , DG_XML. <br> - * List of values will be extended in post-1510 releases. - */ - ArtifactTypeEnum getArtifactType(); - - /** - * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br> - * The full artifact URL will be in the following format :<br> - * https://{serverBaseURL}/{resourcePath}<br> - * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br> - * resourcePath - "artifactURL" <br> - * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml - */ - String getArtifactURL(); - - /** - * Base-64 encoded MD5 checksum of the artifact's payload.<br> - * Should be used for data integrity validation when an artifact's payload is downloaded.<br> - */ - String getArtifactChecksum(); - - /** - * Installation timeout. Used by the orchestrator. - */ - Integer getArtifactTimeout(); - - /** - * Artifact description - */ - String getArtifactDescription(); + /** Artifact File name */ + String getArtifactName(); + + /** + * Artifact Type.<br> + * Following are valid values : HEAT , DG_XML. <br> + * List of values will be extended in post-1510 releases. + */ + ArtifactTypeEnum getArtifactType(); + + /** + * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br> + * The full artifact URL will be in the following format :<br> + * https://{serverBaseURL}/{resourcePath}<br> + * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br> + * resourcePath - "artifactURL" <br> + * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml + */ + String getArtifactURL(); + + /** + * Base-64 encoded MD5 checksum of the artifact's payload.<br> + * Should be used for data integrity validation when an artifact's payload is downloaded.<br> + */ + String getArtifactChecksum(); + + /** + * Installation timeout. Used by the orchestrator. + */ + Integer getArtifactTimeout(); + + /** + * Artifact description + */ + String getArtifactDescription(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java index a27156616b..96abfe087c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,26 +20,35 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import fj.data.Either; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; public interface IDistributionEngine { - public boolean isActive(); + boolean isActive(); + + ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName); + + ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName); + + StorageOperationStatus isEnvironmentAvailable(String envName); + + StorageOperationStatus isEnvironmentAvailable(); - public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName); + /** + * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task. + * + * @param envName + */ + void disableEnvironment(String envName); - public StorageOperationStatus isEnvironmentAvailable(String envName); + StorageOperationStatus isReadyForDistribution(Service service, String envName); - /** - * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task. - * - * @param envName - */ - public void disableEnvironment(String envName); + INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext); - public Either<INotificationData, StorageOperationStatus> isReadyForDistribution(Service service, String distributionId, String envName); + StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service); + OperationalEnvironmentEntry getEnvironmentById(String opEnvId); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java new file mode 100644 index 0000000000..c1b7a313fb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +public interface IDmaapAuditNotificationData { + String getOperationalEnvironmentName(); + String getTenantContext(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java new file mode 100644 index 0000000000..7b974e8a96 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.getEnumValueByFieldValue; + +public interface IDmaapNotificationData { + String getOperationalEnvironmentId(); + + OperationaEnvironmentTypeEnum getOperationalEnvironmentType(); + + DmaapActionEnum getAction(); + + + + + + enum DmaapActionEnum { + DELETE("Delete"), + CREATE("Create"), + UPDATE("Update"), + UNKONW("UNKONW") + + ; + private String actionName; + + private DmaapActionEnum(String actionName) { + this.actionName = actionName; + } + + public String getActionName() { + return actionName; + } + + public static DmaapActionEnum findByName(String actionName){ + return getEnumValueByFieldValue(actionName, DmaapActionEnum.values(), DmaapActionEnum::getActionName, UNKONW, false); + } + }; + enum OperationaEnvironmentTypeEnum { + ECOMP("ECOMP"), + UNKONW("UNKONW") + ; + private String eventTypenName; + + private OperationaEnvironmentTypeEnum(String eventTypenName) { + this.eventTypenName = eventTypenName; + } + + public String getEventTypenName() { + return eventTypenName; + } + + public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName){ + return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(), OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false); + } + }; + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java index d631724701..d66f8f92f1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java @@ -23,84 +23,84 @@ package org.openecomp.sdc.be.components.distribution.engine; import java.util.List; public interface INotificationData { - /** - * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br> - * Generated UUID is compliant with RFC 4122.<br> - * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> - * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getDistributionID(); - - /** Logical Service Name. */ - String getServiceName(); - - /** - * Service Version.<br> - * Two dot (".") separated digit blocks.<br> - * Ex. : "2.0" - */ - String getServiceVersion(); - - /** - * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> - * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> - * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getServiceUUID(); - - /** - * Service description - */ - String getServiceDescription(); - - /** - * ServiceInvariant UUID - */ - String getServiceInvariantUUID(); - - /** List of the resource instances */ - List<JsonContainerResourceInstance> getResources(); - - /** List of the artifacts */ - List<ArtifactInfoImpl> getServiceArtifacts(); - - String getWorkloadContext(); - - void setDistributionID(String distributionId); - - /** Logical Service Name. */ - void setServiceName(String serviceName); - - /** - * Service Version.<br> - * Two dot (".") separated digit blocks.<br> - * Ex. : "2.0" - */ - void setServiceVersion(String serviceVersion); - - /** - * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> - * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> - * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 - */ - void setServiceUUID(String serviceUUID); - - /** - * Service Description - */ - void setServiceDescription(String serviceDescription); - - /** - * ServiceInvariant UUID - */ - void setServiceInvariantUUID(String serviceInvariantUuid); - - /** List of the Resource Instances */ - void setResources(List<JsonContainerResourceInstance> resource); - - /** List of the Resource Instances */ - void setServiceArtifacts(List<ArtifactInfoImpl> artifacts); - - void setWorkloadContext(String workloadContext); + /** + * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br> + * Generated UUID is compliant with RFC 4122.<br> + * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> + * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getDistributionID(); + + /** Logical Service Name. */ + String getServiceName(); + + /** + * Service Version.<br> + * Two dot (".") separated digit blocks.<br> + * Ex. : "2.0" + */ + String getServiceVersion(); + + /** + * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> + * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> + * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getServiceUUID(); + + /** + * Service description + */ + String getServiceDescription(); + + /** + * ServiceInvariant UUID + */ + String getServiceInvariantUUID(); + + /** List of the resource instances */ + List<JsonContainerResourceInstance> getResources(); + + /** List of the artifacts */ + List<ArtifactInfoImpl> getServiceArtifacts(); + + String getWorkloadContext(); + + void setDistributionID(String distributionId); + + /** Logical Service Name. */ + void setServiceName(String serviceName); + + /** + * Service Version.<br> + * Two dot (".") separated digit blocks.<br> + * Ex. : "2.0" + */ + void setServiceVersion(String serviceVersion); + + /** + * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> + * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br> + * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 + */ + void setServiceUUID(String serviceUUID); + + /** + * Service Description + */ + void setServiceDescription(String serviceDescription); + + /** + * ServiceInvariant UUID + */ + void setServiceInvariantUUID(String serviceInvariantUuid); + + /** List of the Resource Instances */ + void setResources(List<JsonContainerResourceInstance> resource); + + /** List of the Resource Instances */ + void setServiceArtifacts(List<ArtifactInfoImpl> artifacts); + + void setWorkloadContext(String workloadContext); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java new file mode 100644 index 0000000000..a1936c61dd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +public interface INotificationHandler { + /** + * Allows to handle received topic message + * @param notification + * @return true if finished successfully otherwise false + */ + public boolean handleMessage(String notification); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java index 9a77b9f94f..deac8751b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java @@ -22,18 +22,18 @@ package org.openecomp.sdc.be.components.distribution.engine; public interface IResourceArtifactInfo extends IArtifactInfo { - /** resource name */ - String getResourceName(); + /** resource name */ + String getResourceName(); - /** resource version */ - String getResourceVersion(); + /** resource version */ + String getResourceVersion(); - /** - * Global UUID of the resource that specific artifact belongs to.<br> - * It is generated by ASDC per each resource version.<br> - * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-"). <br> - * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getResourceUUID(); + /** + * Global UUID of the resource that specific artifact belongs to.<br> + * It is generated by ASDC per each resource version.<br> + * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-"). <br> + * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getResourceUUID(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java index 5efcfe7fa8..db0e1e938d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java @@ -20,109 +20,129 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.List; - import org.openecomp.sdc.be.model.ComponentInstance; +import java.util.List; + public class JsonContainerResourceInstance { - private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory; - private List<ArtifactInfoImpl> artifacts; - - public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) { - super(); - this.resourceInstanceName = resourceInstance.getName(); - this.resourceName = resourceInstance.getComponentName(); - this.resourceVersion = resourceInstance.getComponentVersion(); - this.resoucreType = resourceType; - this.resourceUUID = resourceInstance.getComponentUid(); - this.artifacts = artifacts; - this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); - } - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResoucreType() { - return resoucreType; - } - - public void setResoucreType(String resoucreType) { - this.resoucreType = resoucreType; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public List<ArtifactInfoImpl> getArtifacts() { - return artifacts; - } - - public void setArtifacts(List<ArtifactInfoImpl> artifacts) { - this.artifacts = artifacts; - } - - public String getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(String resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceCustomizationUUID() { - return resourceCustomizationUUID; - } - - public void setResourceCustomizationUUID(String customizationUUID) { - this.resourceCustomizationUUID = customizationUUID; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } - - @Override - public String toString() { - return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID - + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; - } - + private String resourceInstanceName; + private String resourceName; + private String resourceVersion; + private String resourceType; + private String resourceUUID; + private String resourceInvariantUUID; + private String resourceCustomizationUUID; + private String category; + private String subcategory; + private List<ArtifactInfoImpl> artifacts; + + public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) { + super(); + this.resourceInstanceName = resourceInstance.getName(); + this.resourceName = resourceInstance.getComponentName(); + this.resourceVersion = resourceInstance.getComponentVersion(); + this.resourceType = resourceType; + this.resourceUUID = resourceInstance.getComponentUid(); + this.artifacts = artifacts; + this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); + } + + public JsonContainerResourceInstance(ComponentInstance resourceInstance, List<ArtifactInfoImpl> artifacts) { + super(); + this.resourceInstanceName = resourceInstance.getName(); + this.resourceName = resourceInstance.getComponentName(); + this.resourceVersion = resourceInstance.getComponentVersion(); + if(resourceInstance.getOriginType() != null) + this.resourceType = resourceInstance.getOriginType().getValue(); + this.resourceUUID = resourceInstance.getComponentUid(); + this.artifacts = artifacts; + this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resourceType; + } + + public void setResoucreType(String resoucreType) { + this.resourceType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List<ArtifactInfoImpl> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<ArtifactInfoImpl> artifacts) { + this.artifacts = artifacts; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceCustomizationUUID() { + return resourceCustomizationUUID; + } + + public void setResourceCustomizationUUID(String customizationUUID) { + this.resourceCustomizationUUID = customizationUUID; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + @Override + public String toString() { + return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resourceType + ", resourceUUID=" + resourceUUID + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java index 353039647d..1db67a9581 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java @@ -24,111 +24,111 @@ import java.util.List; public class NotificationDataImpl implements INotificationData { - private String distributionID; - private String serviceName; - private String serviceVersion; - private String serviceUUID; - private String serviceDescription; - private String serviceInvariantUUID; - private List<JsonContainerResourceInstance> resources; - private List<ArtifactInfoImpl> serviceArtifacts; - private String workloadContext; - - @Override - public String getDistributionID() { - return distributionID; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getServiceVersion() { - return serviceVersion; - } - - @Override - public String getServiceUUID() { - return serviceUUID; - } - - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public void setServiceVersion(String serviceVersion) { - this.serviceVersion = serviceVersion; - } - - public void setServiceUUID(String serviceUUID) { - this.serviceUUID = serviceUUID; - } - - public String getServiceDescription() { - return serviceDescription; - } - - public void setServiceDescription(String serviceDescription) { - this.serviceDescription = serviceDescription; - } - @Override - public String getWorkloadContext() { return workloadContext; } - - @Override - public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } - - @Override - public String toString() { - return "NotificationDataImpl{" + - "distributionID='" + distributionID + '\'' + - ", serviceName='" + serviceName + '\'' + - ", serviceVersion='" + serviceVersion + '\'' + - ", serviceUUID='" + serviceUUID + '\'' + - ", serviceDescription='" + serviceDescription + '\'' + - ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + - ", resources=" + resources + - ", serviceArtifacts=" + serviceArtifacts + - ", workloadContext='" + workloadContext + '\'' + - '}'; - } - - @Override - public List<JsonContainerResourceInstance> getResources() { - return resources; - } - - @Override - public void setResources(List<JsonContainerResourceInstance> resources) { - this.resources = resources; - - } - - @Override - public List<ArtifactInfoImpl> getServiceArtifacts() { - // TODO Auto-generated method stub - return serviceArtifacts; - } - - @Override - public void setServiceArtifacts(List<ArtifactInfoImpl> serviceArtifacts) { - this.serviceArtifacts = serviceArtifacts; - - } - - @Override - public String getServiceInvariantUUID() { - return serviceInvariantUUID; - } - - @Override - public void setServiceInvariantUUID(String serviceInvariantUUID) { - this.serviceInvariantUUID = serviceInvariantUUID; - } + private String distributionID; + private String serviceName; + private String serviceVersion; + private String serviceUUID; + private String serviceDescription; + private String serviceInvariantUUID; + private List<JsonContainerResourceInstance> resources; + private List<ArtifactInfoImpl> serviceArtifacts; + private String workloadContext; + + @Override + public String getDistributionID() { + return distributionID; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getServiceVersion() { + return serviceVersion; + } + + @Override + public String getServiceUUID() { + return serviceUUID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + @Override + public String getWorkloadContext() { return workloadContext; } + + @Override + public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } + + @Override + public String toString() { + return "NotificationDataImpl{" + + "distributionID='" + distributionID + '\'' + + ", serviceName='" + serviceName + '\'' + + ", serviceVersion='" + serviceVersion + '\'' + + ", serviceUUID='" + serviceUUID + '\'' + + ", serviceDescription='" + serviceDescription + '\'' + + ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + + ", resources=" + resources + + ", serviceArtifacts=" + serviceArtifacts + + ", workloadContext='" + workloadContext + '\'' + + '}'; + } + + @Override + public List<JsonContainerResourceInstance> getResources() { + return resources; + } + + @Override + public void setResources(List<JsonContainerResourceInstance> resources) { + this.resources = resources; + + } + + @Override + public List<ArtifactInfoImpl> getServiceArtifacts() { + // TODO Auto-generated method stub + return serviceArtifacts; + } + + @Override + public void setServiceArtifacts(List<ArtifactInfoImpl> serviceArtifacts) { + this.serviceArtifacts = serviceArtifacts; + + } + + @Override + public String getServiceInvariantUUID() { + return serviceInvariantUUID; + } + + @Override + public void setServiceInvariantUUID(String serviceInvariantUUID) { + this.serviceInvariantUUID = serviceInvariantUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java index 74fbb2c660..dc58a24e5f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java @@ -20,62 +20,57 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - +import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.util.concurrent.*; public class NotificationExecutorService { - private static Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class); - public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) { + public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) { - Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize(); - if (minThreadPoolSize == null) { - minThreadPoolSize = 0; - } + Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize(); + if (minThreadPoolSize == null) { + minThreadPoolSize = 0; + } - Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize(); - if (maxThreadPoolSize == null) { - maxThreadPoolSize = 10; - } + Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize(); + if (maxThreadPoolSize == null) { + maxThreadPoolSize = 10; + } - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d"); - ThreadFactory threadFactory = threadFactoryBuilder.build(); + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d"); + ThreadFactory threadFactory = threadFactoryBuilder.build(); - ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); + ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); - return executorService; - } + return executorService; + } - public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) { + public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) { - logger.debug("shutdown NotificationExecutorService"); - pool.shutdown(); // Disable new tasks from being submitted - try { - // Wait a while for existing tasks to terminate - if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { - pool.shutdownNow(); // Cancel currently executing tasks - // Wait a while for tasks to respond to being cancelled - if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { - logger.debug("Failed to close executor service"); - } - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - pool.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } + logger.debug("shutdown NotificationExecutorService"); + pool.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { + pool.shutdownNow(); // Cancel currently executing tasks + // Wait a while for tasks to respond to being cancelled + if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { + logger.debug("Failed to close executor service"); + } + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + pool.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java deleted file mode 100644 index c283ecc92b..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java +++ /dev/null @@ -1,156 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.distribution.engine; - -import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PublishNotificationRunnable implements Runnable { - - private String envName; - private String distributionId; - private Service service; - private INotificationData data; - private DistributionEngineConfiguration deConfiguration; - private String topicName; - private CambriaHandler cambriaHandler; - private ComponentsUtils componentUtils; - private String userId; - private String modifierName; - private String requestId; - - private static Logger logger = LoggerFactory.getLogger(PublishNotificationRunnable.class.getName()); - - public PublishNotificationRunnable(String envName, String distributionId, Service service, INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName, String userId, String modifierName, - CambriaHandler cambriaHandler, ComponentsUtils componentUtils, String requestId) { - super(); - this.envName = envName; - this.distributionId = distributionId; - this.service = service; - this.data = data; - this.deConfiguration = deConfiguration; - this.topicName = topicName; - this.cambriaHandler = cambriaHandler; - this.componentUtils = componentUtils; - this.userId = userId; - this.modifierName = modifierName; - this.requestId = requestId; - } - - public INotificationData getData() { - return data; - } - - public void setData(INotificationData data) { - this.data = data; - } - - public DistributionEngineConfiguration getDeConfiguration() { - return deConfiguration; - } - - public void setDeConfiguration(DistributionEngineConfiguration deConfiguration) { - this.deConfiguration = deConfiguration; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getModifierName() { - return modifierName; - } - - public void setModifierName(String modifierName) { - this.modifierName = modifierName; - } - - @Override - public void run() { - - long startTime = System.currentTimeMillis(); - ThreadLocalsHolder.setUuid(this.requestId); - - CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data, - deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds()); - - logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode()); - auditDistributionNotification(topicName, status, service, distributionId, envName, userId, modifierName); - - long endTime = System.currentTimeMillis(); - logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime)); - - } - - private void auditDistributionNotification(String topicName, CambriaErrorResponse status, Service service, String distributionId, String envName, String userId, String modifierName) { - if (this.componentUtils != null) { - Integer httpCode = status.getHttpCode(); - String httpCodeStr = String.valueOf(httpCode); - - String desc = getDescriptionFromErrorResponse(status); - - this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envName, service.getLifecycleState().name(), topicName, - distributionId, desc, httpCodeStr); - } - } - - private String getDescriptionFromErrorResponse(CambriaErrorResponse status) { - - CambriaOperationStatus operationStatus = status.getOperationStatus(); - - switch (operationStatus) { - case OK: - return "OK"; - case AUTHENTICATION_ERROR: - return "Error: Authentication problem towards U-EB server"; - case INTERNAL_SERVER_ERROR: - return "Error: Internal U-EB server error"; - case UNKNOWN_HOST_ERROR: - return "Error: Cannot reach U-EB server host"; - case CONNNECTION_ERROR: - return "Error: Cannot connect to U-EB server"; - case OBJECT_NOT_FOUND: - return "Error: object not found in U-EB server"; - default: - return "Error: Internal Cambria server problem"; - - } - - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java index 31f3cb6fda..19a857a115 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java @@ -22,37 +22,37 @@ package org.openecomp.sdc.be.components.distribution.engine; public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResourceArtifactInfo { - private String resourceName; - private String resourceVersion; - private String resourceUUID; - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - @Override - public String toString() { - return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]"; - } + private String resourceName; + private String resourceVersion; + private String resourceUUID; + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + @Override + public String toString() { + return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java index 50d1700f37..1d626805f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java @@ -22,9 +22,9 @@ package org.openecomp.sdc.be.components.distribution.engine; public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServiceArtifactInfo { - @Override - public String toString() { - return "ServiceArtifactInfoImpl [" + super.toString() + "]"; - } + @Override + public String toString() { + return "ServiceArtifactInfoImpl [" + super.toString() + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java index 0330a756c6..f3d17979ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java @@ -20,26 +20,16 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.slf4j.Logger; @@ -47,279 +37,224 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; +import java.util.stream.Collectors; @Component("serviceDistributionArtifactsBuilder") public class ServiceDistributionArtifactsBuilder { - private int defaultArtifactInstallTimeout = 60; - - private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName()); - - final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; - final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s"; - final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; - - final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; - - @javax.annotation.Resource - InterfaceLifecycleOperation interfaceLifecycleOperation; - - @javax.annotation.Resource - IArtifactOperation artifactOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - /* - * @javax.annotation.Resource private - * InformationDeployedArtifactsBusinessLogic - * informationDeployedArtifactsBusinessLogic; - */ - - @PostConstruct - private void init() { - defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration() - .getDefaultHeatArtifactTimeoutMinutes(); - } - - public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { - return interfaceLifecycleOperation; - } - - public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { - this.interfaceLifecycleOperation = interfaceLifecycleOperation; - } - - public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId) { - INotificationData notificationData = new NotificationDataImpl(); - - notificationData.setResources(convertRIToJsonContanier(service)); - notificationData.setServiceName(service.getName()); - notificationData.setServiceVersion(service.getVersion()); - notificationData.setDistributionID(distributionId); - notificationData.setServiceUUID(service.getUUID()); - notificationData.setServiceDescription(service.getDescription()); - notificationData.setServiceInvariantUUID(service.getInvariantUUID()); - String workloadContext= ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); - if(workloadContext!=null){ - notificationData.setWorkloadContext(workloadContext); - } - logger.debug("Before returning notification data object {}", notificationData); - - return notificationData; - - } - - public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) { - - notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service)); - - logger.debug("Before returning notification data object {}", notificationData); - - return notificationData; - - } - - private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) { - - Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts(); - List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream() - //filters all artifacts with existing EsId - .filter(artifactDef -> artifactDef.checkEsIdExist()) - //collects all filtered artifacts with existing EsId to List - .collect(Collectors.toList()); - - Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service); - if(toscaTemplateArtifactOptl.isPresent()){ - extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); - } - - Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); - if(toscaCsarArtifactOptl.isPresent()){ - extractedServiceArtifacts.add(toscaCsarArtifactOptl.get()); - } - - List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts); - return artifacts; - } - - private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) { - return service.getToscaArtifacts().values().stream() - //filters TOSCA_TEMPLATE artifact - .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny(); - } - - private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) { - return service.getToscaArtifacts().values().stream() - //filters TOSCA_CSAR artifact - .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny(); - } - - private List<JsonContainerResourceInstance> convertRIToJsonContanier(Service service) { - List<JsonContainerResourceInstance> ret = new ArrayList<JsonContainerResourceInstance>(); - if (service.getComponentInstances() != null) { - for (ComponentInstance resourceInstance : service.getComponentInstances()) { - String resoucreType = resourceInstance.getOriginType().getValue(); - List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance); - List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, - artifactsDefList); - - String resourceInvariantUUID = null; - String resourceCategory = null; - String resourceSubcategory = null; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - Either<Resource, StorageOperationStatus> componentResponse = toscaOperationFacade - .getToscaElement(resourceInstance.getComponentUid(), componentParametersView); - - if (componentResponse.isRight()) { - logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid()); - } else { - Resource resource = componentResponse.left().value(); - resourceInvariantUUID = resource.getInvariantUUID(); - - List<CategoryDefinition> categories = resource.getCategories(); - - if (categories != null) { - CategoryDefinition categoryDefinition = categories.get(0); - - if (categoryDefinition != null) { - resourceCategory = categoryDefinition.getName(); - List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories(); - if (null != subcategories) { - SubCategoryDefinition subCategoryDefinition = subcategories.get(0); - - if (subCategoryDefinition != null) { - resourceSubcategory = subCategoryDefinition.getName(); - } - } - } - } - } - - JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType, - rebuildArtifactswith120TimeoutInsteadOf60(artifacts)/*TODO used to send artifacts, the function is a fix to the short timeout bug in distribution*/); - jsonContainer.setResourceInvariantUUID(resourceInvariantUUID); - jsonContainer.setCategory(resourceCategory); - jsonContainer.setSubcategory(resourceSubcategory); - ret.add(jsonContainer); - } - } - return ret; - } - - private List<ArtifactInfoImpl> rebuildArtifactswith120TimeoutInsteadOf60(List<ArtifactInfoImpl> artifacts) { - for(ArtifactInfoImpl artifact : artifacts){ - if(artifact.getArtifactTimeout().equals(60)){ - artifact.setArtifactTimeout(120); - } - } - return artifacts; - } - - private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) { - List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>(); - - // List<ArtifactDefinition> informationDeployedArtifacts = - // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance); - List<ArtifactDefinition> deployableArtifacts = new ArrayList<ArtifactDefinition>(); - // deployableArtifacts.addAll(informationDeployedArtifacts); - if (resourceInstance.getDeploymentArtifacts() != null) { - deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values()); - } - - for (ArtifactDefinition artifactDef : deployableArtifacts) { - if (artifactDef.checkEsIdExist()) { - ret.add(artifactDef); - } - } - - return ret; - } - - /** - * build the url for resource intance artifact - * - * @param service - * @param resourceData - * @param artifactName - * @return - */ - public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, - String artifactName) { - - String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), - resourceInstance.getNormalizedName(), artifactName); - - logger.debug("After building artifact url {}", url); - - return url; - } - - /** - * build the url for resource intance artifact - * - * @param service - * @param resourceData - * @param artifactName - * @return - */ - public static String buildServiceArtifactUrl(Service service, String artifactName) { - - String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName); - - logger.debug("After building artifact url {}", url); - - return url; - - } - - /** - * Retrieve all deployment artifacts of all resources under a given service - * - * @param resourceArtifactsResult - * @param service - * @param deConfiguration - * @return - */ - public Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifacts(Service service) { - - Either<Boolean, StorageOperationStatus> result = Either.left(false); - Map<String, ArtifactDefinition> serviseArtifactsMap = service.getDeploymentArtifacts(); - if (serviseArtifactsMap != null && !serviseArtifactsMap.isEmpty()) { - result = Either.left(true); - return result; - } - - List<ComponentInstance> resourceInstances = service.getComponentInstances(); - - if (resourceInstances != null) { - for (ComponentInstance resourceInstance : resourceInstances) { - - Map<String, ArtifactDefinition> deploymentArtifactsMapper = resourceInstance.getDeploymentArtifacts(); - // List<ArtifactDefinition> informationDeployedArtifacts = - // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance); - - boolean isDeployableArtifactFound = isContainsPayload(deploymentArtifactsMapper.values());// || - // isContainsPayload(informationDeployedArtifacts); - if (isDeployableArtifactFound) { - result = Either.left(true); - break; - } - - } - - } - - return result; - } - - private boolean isContainsPayload(Collection<ArtifactDefinition> collection) { - boolean payLoadFound = collection != null && collection.stream().anyMatch(p -> p.checkEsIdExist()); - return payLoadFound; - } + private static final Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class); + + static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; + static final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s"; + static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; + static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; + + @javax.annotation.Resource + InterfaceLifecycleOperation interfaceLifecycleOperation; + + @javax.annotation.Resource + IArtifactOperation artifactOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { + return interfaceLifecycleOperation; + } + + public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { + this.interfaceLifecycleOperation = interfaceLifecycleOperation; + } + + private String resolveWorkloadContext(String workloadContext) { + return workloadContext != null ? workloadContext : + ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); + } + + public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) { + INotificationData notificationData = new NotificationDataImpl(); + + notificationData.setResources(convertRIsToJsonContanier(service)); + notificationData.setServiceName(service.getName()); + notificationData.setServiceVersion(service.getVersion()); + notificationData.setDistributionID(distributionId); + notificationData.setServiceUUID(service.getUUID()); + notificationData.setServiceDescription(service.getDescription()); + notificationData.setServiceInvariantUUID(service.getInvariantUUID()); + workloadContext = resolveWorkloadContext(workloadContext); + if (workloadContext!=null){ + notificationData.setWorkloadContext(workloadContext); + } + logger.debug("Before returning notification data object {}", notificationData); + + return notificationData; + } + + public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) { + + notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service)); + + logger.debug("Before returning notification data object {}", notificationData); + + return notificationData; + } + + private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) { + + Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts(); + List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream() + //filters all artifacts with existing EsId + .filter(ArtifactDefinition::checkEsIdExist) + //collects all filtered artifacts with existing EsId to List + .collect(Collectors.toList()); + + Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service); + if(toscaTemplateArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); + } + + Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); + if(toscaCsarArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaCsarArtifactOptl.get()); + } + + return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts); + } + + private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_TEMPLATE artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny(); + } + + private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_CSAR artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny(); + } + + private List<JsonContainerResourceInstance> convertRIsToJsonContanier(Service service) { + List<JsonContainerResourceInstance> ret = new ArrayList<>(); + if (service.getComponentInstances() != null) { + for (ComponentInstance instance : service.getComponentInstances()) { + JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance)); + ComponentParametersView filter = new ComponentParametersView(); + filter.disableAll(); + filter.setIgnoreCategories(false); + toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter) + .left() + .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);}) + .right() + .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid())); + ret.add(jsonContainer); + } + } + return ret; + } + + private void fillJsonContainer(JsonContainerResourceInstance jsonContainer, Resource resource) { + jsonContainer.setResourceInvariantUUID(resource.getInvariantUUID()); + setCategories(jsonContainer, resource.getCategories()); + } + + private List<ArtifactInfoImpl> convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) { + List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance)); + artifacts.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout); + return artifacts; + } + + private void setCategories(JsonContainerResourceInstance jsonContainer, List<CategoryDefinition> categories) { + if (categories != null) { + CategoryDefinition categoryDefinition = categories.get(0); + + if (categoryDefinition != null) { + jsonContainer.setCategory(categoryDefinition.getName()); + List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories(); + if (null != subcategories) { + SubCategoryDefinition subCategoryDefinition = subcategories.get(0); + + if (subCategoryDefinition != null) { + jsonContainer.setSubcategory(subCategoryDefinition.getName()); + } + } + } + } + } + + private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) { + List<ArtifactDefinition> ret = new ArrayList<>(); + + List<ArtifactDefinition> deployableArtifacts = new ArrayList<>(); + if (resourceInstance.getDeploymentArtifacts() != null) { + deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values()); + } + + for (ArtifactDefinition artifactDef : deployableArtifacts) { + if (artifactDef.checkEsIdExist()) { + ret.add(artifactDef); + } + } + + return ret; + } + + /** + * build the URL for resource instance artifact + * + * @param service + * @param resourceInstance + * @param artifactName + * @return URL string + */ + public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, + String artifactName) { + + String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), + resourceInstance.getNormalizedName(), artifactName); + + logger.debug("After building artifact url {}", url); + + return url; + } + + /** + * build the URL for resource instance artifact + * + * @param service + * @param artifactName + * @return URL string + */ + public static String buildServiceArtifactUrl(Service service, String artifactName) { + + String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName); + + logger.debug("After building artifact url {}", url); + + return url; + + } + + /** + * Verifies that the service or at least one of its instance contains deployment artifacts + * + * @param the service + * @return boolean + */ + public boolean verifyServiceContainsDeploymentArtifacts(Service service) { + if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) { + return true; + } + boolean contains = false; + List<ComponentInstance> resourceInstances = service.getComponentInstances(); + if (CollectionUtils.isNotEmpty(resourceInstances)) { + contains = resourceInstances.stream().anyMatch(i -> isContainsPayload(i.getDeploymentArtifacts())); + } + return contains; + } + + private boolean isContainsPayload(Map<String, ArtifactDefinition> deploymentArtifacts) { + return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java index f8c0e3f593..3477648dbd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine; public enum SubscriberTypeEnum { - CONSUMER, PRODUCER; + CONSUMER, PRODUCER; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java index c522ca91b5..7a25c2ed69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java @@ -20,58 +20,58 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.Callable; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.Callable; + public class UebHealthCheckCall implements Callable<Boolean> { - CambriaHandler cambriaHandler = new CambriaHandler(); + CambriaHandler cambriaHandler = new CambriaHandler(); - String server; - String publicApiKey; + String server; + String publicApiKey; - private static Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); + private static final Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); - private static Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class); - public UebHealthCheckCall(String server, String publicApiKey) { - super(); - this.server = server; - this.publicApiKey = publicApiKey; - } + public UebHealthCheckCall(String server, String publicApiKey) { + super(); + this.server = server; + this.publicApiKey = publicApiKey; + } - @Override - public Boolean call() { + @Override + public Boolean call() { - healthLogger.trace("Going to run health check towards ueb server {}", server); + healthLogger.trace("Going to run health check towards ueb server {}", server); - boolean result = false; - CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey); + boolean result = false; + CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey); - logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse); + logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse); - if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) { - logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode); - result = true; - } + if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) { + logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode); + result = true; + } - healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result); + healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result); - return result; - } + return result; + } - public String getServer() { - return server; - } + public String getServer() { + return server; + } - public CambriaHandler getCambriaHandler() { - return cambriaHandler; - } + public CambriaHandler getCambriaHandler() { + return cambriaHandler; + } - public void setCambriaHandler(CambriaHandler cambriaHandler) { - this.cambriaHandler = cambriaHandler; - } + public void setCambriaHandler(CambriaHandler cambriaHandler) { + this.cambriaHandler = cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java index d706e40f5c..8f0865f2ac 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java @@ -20,105 +20,100 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.common.api.Constants; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + public class VfModuleArtifactPayload { - - private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; - private Boolean isBase; - private List<String> artifacts; - private Map< String, Object> properties; - - public VfModuleArtifactPayload(GroupDefinition group) { - vfModuleModelName = group.getName(); - vfModuleModelInvariantUUID = group.getInvariantUUID(); - vfModuleModelVersion = group.getVersion(); - vfModuleModelUUID = group.getGroupUUID(); - vfModuleModelDescription = group.getDescription(); - - artifacts = group.getArtifactsUuid(); - // Base Value is set from properties - setBaseValue(group); - - } - - public VfModuleArtifactPayload(GroupInstance group) { - vfModuleModelName = group.getGroupName(); - vfModuleModelInvariantUUID = group.getInvariantUUID(); - vfModuleModelVersion = group.getVersion(); - vfModuleModelUUID = group.getGroupUUID(); - vfModuleModelCustomizationUUID = group.getCustomizationUUID(); - vfModuleModelDescription = group.getDescription(); - - artifacts = group.getArtifactsUuid(); - artifacts.addAll(group.getGroupInstanceArtifactsUuid()); - - // Base Value is set from properties - setBaseValue(group); - - if(group.convertToGroupInstancesProperties() != null) - setProperties(group.convertToGroupInstancesProperties()); - //converts List of GroupInstanceProperties to Map propertyName : GroupInstanceProperty () - //setProperties(group.getGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p))); - - } - - private void setBaseValue(GroupInstance group) { - if (group.convertToGroupInstancesProperties() != null) { - Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (findBaseProperty.isPresent()) { - isBase = Boolean.valueOf(findBaseProperty.get().getValue()); - } - - } - } - private void setBaseValue(GroupDefinition group) { - if (group.getProperties() != null) { - Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (findBaseProperty.isPresent()) { - isBase = Boolean.valueOf(findBaseProperty.get().getValue()); - } - - } - } - - - - public List<String> getArtifacts() { - return artifacts; - } - - public void setArtifacts(List<String> artifacts) { - this.artifacts = artifacts; - } - - - - public Map<String, Object> getProperties() { - return properties; - } - - /*public void setProperties(Map<String, Object> properties) { - this.properties = properties; - }*/ - - public void setProperties(List<GroupInstanceProperty> properties) { - this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect( - Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() )); - } - - public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) { - Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); - Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); - return thisCounter.compareTo(otherCounter); - } + + private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; + private Boolean isBase; + private List<String> artifacts; + private Map< String, Object> properties; + + public VfModuleArtifactPayload(GroupDefinition group) { + vfModuleModelName = group.getName(); + vfModuleModelInvariantUUID = group.getInvariantUUID(); + vfModuleModelVersion = group.getVersion(); + vfModuleModelUUID = group.getGroupUUID(); + vfModuleModelDescription = group.getDescription(); + + artifacts = group.getArtifactsUuid(); + // Base Value is set from properties + setBaseValue(group); + + } + + public VfModuleArtifactPayload(GroupInstance group) { + vfModuleModelName = group.getGroupName(); + vfModuleModelInvariantUUID = group.getInvariantUUID(); + vfModuleModelVersion = group.getVersion(); + vfModuleModelUUID = group.getGroupUUID(); + vfModuleModelCustomizationUUID = group.getCustomizationUUID(); + vfModuleModelDescription = group.getDescription(); + + artifacts = new ArrayList<>(group.getArtifactsUuid()); + artifacts.addAll(group.getGroupInstanceArtifactsUuid()); + + // Base Value is set from properties + setBaseValue(group); + + if(group.convertToGroupInstancesProperties() != null) + setProperties(group.convertToGroupInstancesProperties()); + } + + private void setBaseValue(GroupInstance group) { + if (group.convertToGroupInstancesProperties() != null) { + Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (findBaseProperty.isPresent()) { + isBase = Boolean.valueOf(findBaseProperty.get().getValue()); + } + + } + } + private void setBaseValue(GroupDefinition group) { + if (group.getProperties() != null) { + Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (findBaseProperty.isPresent()) { + isBase = Boolean.valueOf(findBaseProperty.get().getValue()); + } + + } + } + + + + public List<String> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<String> artifacts) { + this.artifacts = artifacts; + } + + + + public Map<String, Object> getProperties() { + return properties; + } + + + public void setProperties(List<GroupInstanceProperty> properties) { + this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect( + Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() )); + } + + public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) { + Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); + Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); + return thisCounter.compareTo(otherCounter); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java new file mode 100644 index 0000000000..e6f2cc634f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.distribution.engine.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan({"org.openecomp.sdc.be.components.distribution.engine", + }) +public class DistributionEngineSpringConfig { + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java new file mode 100644 index 0000000000..7f9dd45e67 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.be.components.distribution.engine.report; + +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification; + +public interface DistributionCompleteReporter { + + void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java new file mode 100644 index 0000000000..4e06b0ed0e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.components.distribution.engine.report; + +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification; +import org.openecomp.sdc.be.components.distribution.engine.rest.MSORestClient; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +@Component +public class MsoDistributionCompleteReporter implements DistributionCompleteReporter { + + @Resource + private MSORestClient msoClient; + + @Override + public void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification) { + msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(), distributionStatusNotification.getErrorReason()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java new file mode 100644 index 0000000000..45727fb28f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +/** + * a class which represents an MSO distribution status rest request body + */ +public class DistributionStatusRequest { + + private String status; + private String errorReason; + + public DistributionStatusRequest(String status, String errorReason) { + this.status = status; + this.errorReason = errorReason; + } + + public String getStatus() { + return status; + } + + public String getErrorReason() { + return errorReason; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java new file mode 100644 index 0000000000..76263f942d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java @@ -0,0 +1,69 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.eclipse.jetty.util.URIUtil; +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.*; +import org.openecomp.sdc.common.http.config.BasicAuthorization; +import org.openecomp.sdc.common.http.config.ExternalServiceConfig; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.Properties; + +@Component +public class MSORestClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(MSORestClient.class); + private static final Gson gson = new Gson(); + @VisibleForTesting + static final String DISTRIBUTIONS_RESOURCE_CONFIG_PARAM = "distributions"; + + private ExternalServiceConfig serviceConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig(); + + public MSORestClient() { + HttpClientConfig httpClientConfig = serviceConfig.getHttpClientConfig(); + int numOfRetries = httpClientConfig.getNumOfRetries(); + if ( numOfRetries > 0 ) { + httpClientConfig.setRetryHandler(RetryHandlers.getDefault(numOfRetries)); + } + } + + public HttpResponse<String> notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) { + try { + return doNotifyDistributionComplete(distributionId, distributionStatusEnum, errReason); + } + catch(HttpExecuteException e) { + LOGGER.debug("The request to mso failed with exception ", e); + return Responses.INTERNAL_SERVER_ERROR; + } + } + + private HttpResponse<String> doNotifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) throws HttpExecuteException { + StringEntity entity = new StringEntity(gson.toJson(new DistributionStatusRequest(distributionStatusEnum.name(), errReason)), ContentType.APPLICATION_JSON); + HttpResponse<String> response = HttpRequest.patch(buildMsoDistributionUrl(distributionId), buildReqHeader(), entity, serviceConfig.getHttpClientConfig()); + LOGGER.info("response from mso - status code: {}, status description: {}, response: {}, ", response.getStatusCode(), response.getDescription(), response.getResponse()); + return response; + } + + private Properties buildReqHeader() { + Properties properties = new Properties(); + BasicAuthorization basicAuth = serviceConfig.getHttpClientConfig().getBasicAuthorization(); + RestUtils.addBasicAuthHeader(properties, basicAuth.getUserName(), basicAuth.getPassword()); + return properties; + } + + private String buildMsoDistributionUrl(String distributionId) { + String msoBaseUrl = serviceConfig.getHttpRequestConfig().getServerRootUrl(); + String distributionsPath = serviceConfig.getHttpRequestConfig().getResourceNamespaces().get(DISTRIBUTIONS_RESOURCE_CONFIG_PARAM); + String distributionsApiPath = distributionsPath + URIUtil.SLASH + distributionId; + return msoBaseUrl + distributionsApiPath; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java new file mode 100644 index 0000000000..670350a733 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java @@ -0,0 +1,475 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.health; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; +import org.openecomp.sdc.be.components.distribution.engine.DmaapHealth; +import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; +import org.openecomp.sdc.be.components.impl.CassandraHealthCheck; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.impl.EsHealthCheckDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.openecomp.sdc.common.http.config.Timeouts; +import org.openecomp.sdc.common.util.HealthCheckUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.stream.Collectors; + +import static java.lang.String.format; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; +import static org.apache.http.HttpStatus.SC_OK; +import static org.openecomp.sdc.common.api.Constants.*; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP; +import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion; + + +@Component("healthCheckBusinessLogic") +public class HealthCheckBusinessLogic { + + protected static final String BE_HEALTH_LOG_CONTEXT = "be.healthcheck"; + private static final String BE_HEALTH_CHECK_STR = "beHealthCheck"; + private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s"; + private static final Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT); + private static final Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName()); + private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil(); + ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task")); + HealthCheckScheduledTask healthCheckScheduledTask = null; + @Resource + private TitanGenericDao titanGenericDao; + @Resource + private EsHealthCheckDao esHealthCheckDao; + @Resource + private DistributionEngineClusterHealth distributionEngineClusterHealth; + @Resource + private DmaapHealth dmaapHealth; + @Resource + private CassandraHealthCheck cassandraHealthCheck; + @Autowired + private SwitchoverDetector switchoverDetector; + private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null; + private ScheduledFuture<?> scheduledFuture = null; + + @PostConstruct + public void init() { + + prevBeHealthCheckInfos = getBeHealthCheckInfos(); + + log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos); + + healthCheckScheduledTask = new HealthCheckScheduledTask(); + + if (this.scheduledFuture == null) { + this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, SECONDS); + } + + } + + public boolean isDistributionEngineUp() { + + HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); + return !healthCheckInfo.getHealthCheckStatus().equals(DOWN); + } + + public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() { + Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); + return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos); + } + + private List<HealthCheckInfo> getBeHealthCheckInfos() { + + log.trace("In getBeHealthCheckInfos"); + + List<HealthCheckInfo> healthCheckInfos = new ArrayList<>(); + + //Dmaap + getDmaapHealthCheck(healthCheckInfos); + // BE + getBeHealthCheck(healthCheckInfos); + + // Titan + getTitanHealthCheck(healthCheckInfos); + // ES + getEsHealthCheck(healthCheckInfos); + + // Distribution Engine + getDistributionEngineCheck(healthCheckInfos); + + //Cassandra + getCassandraHealthCheck(healthCheckInfos); + + // Amdocs + getAmdocsHealthCheck(healthCheckInfos); + + //DCAE + getDcaeHealthCheck(healthCheckInfos); + + return healthCheckInfos; + } + + private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + + // ES health check and version + String appVersion = getAppVersion(); + HealthCheckStatus healthCheckStatus; + String description; + + try { + healthCheckStatus = esHealthCheckDao.getClusterHealthStatus(); + } catch (Exception e) { + healthCheckStatus = DOWN; + description = "ES cluster error: " + e.getMessage(); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description)); + return healthCheckInfos; + } + if (healthCheckStatus.equals(DOWN)) { + description = "ES cluster is down"; + } else { + description = "OK"; + } + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description)); + return healthCheckInfos; + } + + private List<HealthCheckInfo> getBeHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + String appVersion = getAppVersion(); + String description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, appVersion, description)); + return healthCheckInfos; + } + + private List<HealthCheckInfo> getDmaapHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + String appVersion = getAppVersion(); + dmaapHealth.getHealthCheckInfo().setVersion(appVersion); + healthCheckInfos.add(dmaapHealth.getHealthCheckInfo()); + return healthCheckInfos; + } + + + public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + // Titan health check and version + String description; + boolean isTitanUp; + + try { + isTitanUp = titanGenericDao.isGraphOpen(); + } catch (Exception e) { + description = "Titan error: " + e.getMessage(); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + return healthCheckInfos; + } + if (isTitanUp) { + description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description)); + } else { + description = "Titan graph is down"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + } + return healthCheckInfos; + } + + private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + + String description; + boolean isCassandraUp; + + try { + isCassandraUp = cassandraHealthCheck.getCassandraStatus(); + } catch (Exception e) { + isCassandraUp = false; + log.debug("Cassandra error: " + e.getMessage()); + } + if (isCassandraUp) { + description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UP, null, description)); + } else { + description = "Cassandra is down"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, description)); + } + return healthCheckInfos; + + } + + private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) { + + HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); + + healthCheckInfos.add(healthCheckInfo); + + } + + private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) { + HealthCheckStatus healthCheckStatus; + String description; + String version = null; + List<HealthCheckInfo> componentsInfo = new ArrayList<>(); + final int timeout = 3000; + + if (healthCheckUrl != null) { + try { + HttpResponse<String> httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout))); + int statusCode = httpResponse.getStatusCode(); + String aggDescription = ""; + + if (statusCode == SC_OK || statusCode == SC_INTERNAL_SERVER_ERROR) { + String response = httpResponse.getResponse(); + log.trace("{} Health Check response: {}", componentName, response); + ObjectMapper mapper = new ObjectMapper(); + Map<String, Object> healthCheckMap = mapper.readValue(response, new TypeReference<Map<String, Object>>() { + }); + version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null; + if (healthCheckMap.containsKey("componentsInfo")) { + componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() { + }); + } + + if (!componentsInfo.isEmpty()) { + aggDescription = healthCheckUtil.getAggregateDescription(componentsInfo, null); + } else { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null)); + } + } else { + log.trace("{} Health Check Response code: {}", componentName, statusCode); + } + + if (statusCode != SC_OK) { + healthCheckStatus = DOWN; + description = aggDescription.length() > 0 + ? aggDescription + : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN. + if (componentsInfo.isEmpty()) { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + } else { + healthCheckStatus = UP; + description = "OK"; + } + + } catch (Exception e) { + log.error("{} unexpected response: ", componentName, e); + healthCheckStatus = DOWN; + description = componentName + " unexpected response: " + e.getMessage(); + if (componentsInfo != null && componentsInfo.isEmpty()) { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + } + } else { + healthCheckStatus = DOWN; + description = componentName + " health check Configuration is missing"; + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + + return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo); + } + + @PreDestroy + protected void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (healthCheckScheduler != null) { + healthCheckScheduler.shutdown(); + } + + } + + private void logAlarm(String componentChangedMsg) { + BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg); + } + + public String getSiteMode() { + return switchoverDetector.getSiteMode(); + } + + public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) { + + boolean result = false; + + if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) { + + Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus)); + Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus)); + + if (currentValues != null && prevValues != null) { + int currentSize = currentValues.size(); + int prevSize = prevValues.size(); + + if (currentSize != prevSize) { + + result = true; //extra/missing component + + Map<String, HealthCheckStatus> notPresent = null; + if (currentValues.keySet().containsAll(prevValues.keySet())) { + notPresent = new HashMap<>(currentValues); + notPresent.keySet().removeAll(prevValues.keySet()); + } else { + notPresent = new HashMap<>(prevValues); + notPresent.keySet().removeAll(currentValues.keySet()); + } + + for (String component : notPresent.keySet()) { + logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component))); + } + + } else { + + for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) { + String key = entry.getKey(); + HealthCheckStatus value = entry.getValue(); + + if (!prevValues.containsKey(key)) { + result = true; //component missing + logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); + break; + } + + HealthCheckStatus prevHealthCheckStatus = prevValues.get(key); + + if (value != prevHealthCheckStatus) { + result = true; //component status changed + logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); + break; + } + } + } + } + + } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) { + result = false; + } else { + logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null")); + result = true; + } + + return result; + } + + private String buildOnBoardingHealthCheckUrl() { + + Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); + + if (onboardingConfig != null) { + String protocol = onboardingConfig.getProtocol(); + String host = onboardingConfig.getHost(); + Integer port = onboardingConfig.getPort(); + String uri = onboardingConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } + + log.error("onboarding health check configuration is missing."); + return null; + } + + private String buildDcaeHealthCheckUrl() { + + Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae(); + + if (dcaeConfig != null) { + String protocol = dcaeConfig.getProtocol(); + String host = dcaeConfig.getHost(); + Integer port = dcaeConfig.getPort(); + String uri = dcaeConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } + + log.error("dcae health check configuration is missing."); + return null; + } + + public class HealthCheckScheduledTask implements Runnable { + + List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>(); + + @Override + public void run() { + Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); + healthLogger.trace("Executing BE Health Check Task"); + + List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos(); + boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude()); + + boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()); + + boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos); + + if (prevHealthStatus != healthStatus || anyStatusChanged) { + log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); + + prevBeHealthCheckInfos = currentBeHealthCheckInfos; + logAlarm(healthStatus); + } + + } + + private void logAlarm(boolean prevHealthState) { + if (prevHealthState) { + BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR); + } + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java new file mode 100644 index 0000000000..e0a8533052 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.model.Service; + +/** + * Created by chaya on 10/22/2017. + */ +public class ActivationRequestInformation { + private Service serviceToActivate; + private String workloadContext; + private String tenant; + + public ActivationRequestInformation(Service serviceToActivate, String workloadContext, String tenant) { + this.serviceToActivate = serviceToActivate; + this.workloadContext = workloadContext; + this.tenant = tenant; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public Service getServiceToActivate() { + return serviceToActivate; + } + + public void setServiceToActivate(Service serviceToActivate) { + this.serviceToActivate = serviceToActivate; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java index 51b5679ffa..50331a71d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -52,514 +49,506 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.List; @Component("additionalInformationBusinessLogic") public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation"; - - private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation"; - - private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation"; - - private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation"; - - private static Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class.getName()); - - @javax.annotation.Resource - private IAdditionalInformationOperation additionalInformationOperation = null; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - /** - * Create new additional information on resource/service on graph - * - * @param resourceId - * @param propertyName - * @param newPropertyDefinition - * @param userId - * @return Either<PropertyDefinition, ActionStatus> - */ - public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, CREATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - try { - responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // validate label - responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // validate value - responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(), - additionalInfoParameterInfo.getValue(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, CREATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label)); - return result; - - } else { - AdditionalInformationDefinition informationDefinition = addResult.left().value(); - - AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); - result = Either.left(createdAI); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * Validate the value format. Format the value. - * - * @param additionalInfoParameterInfo - * @return null in case of success. Otherwise response format. - */ - private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { - ResponseFormat result = null; - - String value = additionalInfoParameterInfo.getValue(); - log.debug("Going to validate additional information value {}", value); - - Either<String, ResponseFormat> valueValidRes = validateValue(value); - if (valueValidRes.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); - BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); - result = valueValidRes.right().value(); - } else { - String newValue = valueValidRes.left().value(); - if (log.isTraceEnabled()) { - if (value != null && false == value.equals(newValue)) { - log.trace("The additional information value was normalized from {} to {}", value, newValue); - } - } - additionalInfoParameterInfo.setValue(newValue); - } - return result; - } - - /** - * @param additionalInfoParameterInfo - * @return - */ - private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { - - String key = additionalInfoParameterInfo.getKey(); - log.debug("Going to validate additional information key {}", key); - - ResponseFormat result = null; - ResponseFormat responseFormat; - Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key); - if (validateKeyRes.isRight()) { - responseFormat = validateKeyRes.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); - BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); - result = responseFormat; - - } else { - String convertedKey = validateKeyRes.left().value(); - - if (log.isTraceEnabled()) { - if (key != null && false == key.equals(convertedKey)) { - log.trace("The additional information key {} was normalized to {}", key, convertedKey); - } - } - additionalInfoParameterInfo.setKey(convertedKey); - } - return result; - } - - /** - * verify that the maximal number of additional information properties has not been reached. - * - * @param nodeType - * @param componentId - * @param additionalInfoParameterInfo - * @return response format in case the maximal number has been reached. - */ - private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) { - - ResponseFormat result; - Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys(); - - Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true); - if (checkRes.isRight()) { - StorageOperationStatus status = checkRes.right().value(); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); - return result; - } - Integer currentNumberOfProperties = checkRes.left().value(); - if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) { - log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties); - result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); - return result; - } - - return null; - } - - /** - * validate additional information value - * - * @param value - * @return - */ - private Either<String, ResponseFormat> validateValue(String value) { - - boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value); - if (false == isNonEmptyString) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED)); - } - - boolean valid = StringValidator.getInstance().isValid(value, null); - if (false == valid) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value)); - } - - String converted = StringConvertor.getInstance().convert(value, null, null); - - return Either.left(converted); - } - - private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) { - - for (AdditionalInfoParameterInfo infoParameterInfo : parameters) { - if (infoParameterInfo.getKey().equals(key)) { - return infoParameterInfo; - } - } - return null; - } - - /** - * validate and normalize the key - * - * @param additionalInfoParameterInfo - * @return - */ - private Either<String, ResponseFormat> validateAndNormalizeKey(String key) { - - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setKey(key); - - key = ValidationUtils.normalizeAdditionalInformation(key); - boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key); - if (false == isNonEmptyString) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label)); - } - boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key); - if (false == isValidString) { - if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); - } - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); - } - - return Either.left(key); - } - - /** - * update key and value of a given additional information. - * - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * - Future use - * @param userId - * @return - */ - public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, UPDATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - try { - - // validate input - responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), - additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, UPDATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } else { - AdditionalInformationDefinition informationDefinition = addResult.left().value(); - AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); - result = Either.left(parameterInfo); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * Delete an additional information label - * - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * - Null. Future use. - * @param userId - * @return - */ - public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - return Either.right(responseFormat); - } - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, DELETE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - - Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - if (findIdRes.isRight()) { - StorageOperationStatus status = findIdRes.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, GET_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION); - } - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } - - AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); - - Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, DELETE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } else { - result = Either.left(foundAdditionalInfo); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * @param userId - * @return - */ - public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; - - try { - - Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - - if (findIdRes.isRight()) { - StorageOperationStatus status = findIdRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - } - - AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); - - result = Either.left(foundAdditionalInfo); - - return result; - - } finally { - commitOrRollback(result); - } - - } - - /** - * Get all additional information properties of a given resource/service - * - * @param nodeType - * @param resourceId - * @param additionalInformationUid - * - Future use - * @param userId - * @return - */ - public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<AdditionalInformationDefinition, ResponseFormat> result = null; - - try { - - Either<AdditionalInformationDefinition, TitanOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); - if (findIdRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value()); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus)); - } else { - AdditionalInformationDefinition informationDefinition = findIdRes.left().value(); - result = Either.left(informationDefinition); - } - - return result; - - } finally { - commitOrRollback(result); - } - - } - - private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) { - - switch (nodeType) { - case Resource: - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { - return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } - break; - case Service: - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { - return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } - break; - default: - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName()); - } - - return null; - } + private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation"; + + private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation"; + + private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation"; + + private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation"; + + private static final Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class); + + @javax.annotation.Resource + private IAdditionalInformationOperation additionalInformationOperation = null; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + /** + * Create new additional information on resource/service on graph + * + * @param resourceId + * @param propertyName + * @param newPropertyDefinition + * @param userId + * @return Either<PropertyDefinition, ActionStatus> + */ + public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + try { + responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // validate label + responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // validate value + responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(), + additionalInfoParameterInfo.getValue(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label)); + return result; + + } else { + AdditionalInformationDefinition informationDefinition = addResult.left().value(); + + AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); + result = Either.left(createdAI); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * Validate the value format. Format the value. + * + * @param additionalInfoParameterInfo + * @return null in case of success. Otherwise response format. + */ + private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { + ResponseFormat result = null; + + String value = additionalInfoParameterInfo.getValue(); + log.debug("Going to validate additional information value {}", value); + + Either<String, ResponseFormat> valueValidRes = validateValue(value); + if (valueValidRes.isRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); + result = valueValidRes.right().value(); + } else { + String newValue = valueValidRes.left().value(); + if (log.isTraceEnabled()) { + if (value != null && false == value.equals(newValue)) { + log.trace("The additional information value was normalized from {} to {}", value, newValue); + } + } + additionalInfoParameterInfo.setValue(newValue); + } + return result; + } + + /** + * @param additionalInfoParameterInfo + * @return + */ + private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { + + String key = additionalInfoParameterInfo.getKey(); + log.debug("Going to validate additional information key {}", key); + + ResponseFormat result = null; + ResponseFormat responseFormat; + Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key); + if (validateKeyRes.isRight()) { + responseFormat = validateKeyRes.right().value(); + BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); + result = responseFormat; + + } else { + String convertedKey = validateKeyRes.left().value(); + + if (log.isTraceEnabled()) { + if (key != null && false == key.equals(convertedKey)) { + log.trace("The additional information key {} was normalized to {}", key, convertedKey); + } + } + additionalInfoParameterInfo.setKey(convertedKey); + } + return result; + } + + /** + * verify that the maximal number of additional information properties has not been reached. + * + * @param nodeType + * @param componentId + * @param additionalInfoParameterInfo + * @return response format in case the maximal number has been reached. + */ + private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) { + + ResponseFormat result; + Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys(); + + Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true); + if (checkRes.isRight()) { + StorageOperationStatus status = checkRes.right().value(); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); + return result; + } + Integer currentNumberOfProperties = checkRes.left().value(); + if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) { + log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties); + result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); + return result; + } + + return null; + } + + /** + * validate additional information value + * + * @param value + * @return + */ + private Either<String, ResponseFormat> validateValue(String value) { + + boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value); + if (false == isNonEmptyString) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED)); + } + + boolean valid = StringValidator.getInstance().isValid(value, null); + if (false == valid) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value)); + } + + String converted = StringConvertor.getInstance().convert(value, null, null); + + return Either.left(converted); + } + + private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) { + + for (AdditionalInfoParameterInfo infoParameterInfo : parameters) { + if (infoParameterInfo.getKey().equals(key)) { + return infoParameterInfo; + } + } + return null; + } + + /** + * validate and normalize the key + * + * @param additionalInfoParameterInfo + * @return + */ + private Either<String, ResponseFormat> validateAndNormalizeKey(String key) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setKey(key); + + key = ValidationUtils.normalizeAdditionalInformation(key); + boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key); + if (false == isNonEmptyString) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label)); + } + boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key); + if (false == isValidString) { + if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); + } + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); + } + + return Either.left(key); + } + + /** + * update key and value of a given additional information. + * + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * - Future use + * @param userId + * @return + */ + public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + try { + + // validate input + responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), + additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } else { + AdditionalInformationDefinition informationDefinition = addResult.left().value(); + AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); + result = Either.left(parameterInfo); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * Delete an additional information label + * + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * - Null. Future use. + * @param userId + * @return + */ + public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + return Either.right(responseFormat); + } + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + + Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + if (findIdRes.isRight()) { + StorageOperationStatus status = findIdRes.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION); + } + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } + + AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); + + Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } else { + result = Either.left(foundAdditionalInfo); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * @param userId + * @return + */ + public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<AdditionalInfoParameterInfo, ResponseFormat> result = null; + + try { + + Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + + if (findIdRes.isRight()) { + StorageOperationStatus status = findIdRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + } + + AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); + + result = Either.left(foundAdditionalInfo); + + return result; + + } finally { + commitOrRollback(result); + } + + } + + /** + * Get all additional information properties of a given resource/service + * + * @param nodeType + * @param resourceId + * @param additionalInformationUid + * - Future use + * @param userId + * @return + */ + public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<AdditionalInformationDefinition, ResponseFormat> result = null; + + try { + + Either<AdditionalInformationDefinition, TitanOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); + if (findIdRes.isRight()) { + StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus)); + } else { + AdditionalInformationDefinition informationDefinition = findIdRes.left().value(); + result = Either.left(informationDefinition); + } + + return result; + + } finally { + commitOrRollback(result); + } + + } + + private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) { + + switch (nodeType) { + case Resource: + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { + return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + break; + case Service: + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { + return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + break; + default: + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName()); + } + + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java index 1c5a35453b..fcaf5cdfc6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,6 +29,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Service; +import java.util.*; @org.springframework.stereotype.Component("artifact-resolver") public class ArtifactResolverImpl implements ArtifactsResolver { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index bd7f61444d..39ad806cda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,25 +20,10 @@ package org.openecomp.sdc.be.components.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; - +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; @@ -60,25 +45,12 @@ import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ArtifactType; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; @@ -92,6 +64,7 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.servlets.RepresentationUtils; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.ToscaError; @@ -119,3521 +92,3718 @@ import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.yaml.snakeyaml.Yaml; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - +import javax.servlet.http.HttpServletRequest; +import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - -import fj.data.Either; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("artifactBusinessLogic") public class ArtifactsBusinessLogic extends BaseBusinessLogic { - private static final String ARTIFACT_TYPE_OTHER = "OTHER"; - private static final String ARTIFACT_DESCRIPTION = "artifact description"; - private static final String ARTIFACT_LABEL = "artifact label"; - private static final String ARTIFACT_URL = "artifact url"; - private static final String ARTIFACT_NAME = "artifact name"; - private static final String ARTIFACT_PAYLOAD = "artifact payload"; - - private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; - private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; - private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - - public static final String HEAT_ENV_NAME = "heatEnv"; - public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; - public static final String HEAT_ENV_SUFFIX = "env"; - private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; - - // private static Integer defaultHeatTimeout; - // private static final Integer NON_HEAT_TIMEOUT = 0; - private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static XMLReader parser; - @javax.annotation.Resource - private IInterfaceLifecycleOperation interfaceLifecycleOperation; - @javax.annotation.Resource - private IUserAdminOperation userOperaton; - - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - @javax.annotation.Resource - private UserBusinessLogic userAdminManager; - - @javax.annotation.Resource - private IHeatParametersOperation heatParametersOperation; - - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - - @Autowired - private ToscaExportHandler toscaExportUtils; - - @Autowired - private CsarUtils csarUtils; - - @Autowired - private LifecycleBusinessLogic lifecycleBusinessLogic; - - @Autowired - private IUserBusinessLogic userBusinessLogic; - @Autowired - NodeTemplateOperation nodeTemplateOperation; - - @Autowired - private ArtifactsResolver artifactsResolver; - - public ArtifactsBusinessLogic() { - // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { - // defaultHeatTimeout = 60; - // } - } - - public static enum ArtifactOperationEnum { - Create(), Update(), Delete(), Download(), Link(); - - public static boolean isCreateOrLink(ArtifactOperationEnum operation) { - return (operation.equals(Create) || operation.equals(Link)); - - } - } - - //SAX XML Parser initialization - static { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser newSAXParser = null; - - try { - newSAXParser = spf.newSAXParser(); - parser = newSAXParser.getXMLReader(); - } catch (ParserConfigurationException | SAXException e1) { - log.debug("SAX XML Parser could not been initialized", e1); - } - - try { - parser.setFeature("http://apache.org/xml/features/validation/schema", false); - } catch (SAXNotRecognizedException e) { - log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - - } catch (SAXNotSupportedException e) { - log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - - } - } - - public class ArtifactOperationInfo { - - private ArtifactOperationEnum artifactOperationEnum; - private boolean isExternalApi; - private boolean ignoreLifecycleState; - - public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { - this.artifactOperationEnum = artifactOperationEnum; - this.isExternalApi = isExternalApi; - this.ignoreLifecycleState = ignoreLifecycleState; - } - - public boolean isExternalApi() { - return isExternalApi; - } - - public boolean ignoreLifecycleState() { - return ignoreLifecycleState; - } - - public ArtifactOperationEnum getArtifactOperationEnum() { - return artifactOperationEnum; - } - - } - - // new flow US556184 - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { - return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { - - // step 1 - detect auditing type - AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - // step 2 - check header - if (userId == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); - handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - // step 3 - check user existence - Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); - if (userResult.isRight()) { - return Either.right(userResult.right().value()); - } - - // step 4 - check user's role - User user = userResult.left().value(); - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); - if (validateUserRole.isRight()) { - return Either.right(validateUserRole.right().value()); - } - - // steps 5 - 6 - 7 - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - // ComponentInstance resourceInstance = null; - String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction); - if (validateComponent.isRight()) { - return Either.right(validateComponent.right().value()); - } - component = validateComponent.left().value(); - Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType); - if (validateWorkOnResource.isRight()) { - return Either.right(validateWorkOnResource.right().value()); - } - // step 8 - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component, - shouldLock, inTransaction, true); - - return result; - } - - /** - * This Method validates only the Artifact and does not validate user / role / component ect...<br> - * For regular usage use <br> - * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)} - * - * @return - */ - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, - ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - Component parent = component; - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - - AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction); - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; - if (errorWrapper.isEmpty()) { - // step 10 - result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user, - org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) { - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { - Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction); - if (validateArtifact.isRight()) { - ResponseFormat responseFormat = validateArtifact.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - errorWrapper.setInnerElement(validateArtifact.right().value()); - } else { - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { - artifactInfo = validateArtifact.left().value(); - handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper); - } - } - } - return artifactInfo; - } - - private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock, - Wrapper<ResponseFormat> errorWrapper) { - ArtifactDefinition validatedArtifact = validateArtifact.left().value(); - - if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - if (ComponentTypeEnum.SERVICE == component.getComponentType()) { - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get(); - Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - - ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get(); - Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId); - if (eitherGenerated.isRight()) { - errorWrapper.setInnerElement(eitherGenerated.right().value()); - } - } - } - } - - private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { - boolean needGenerate; - needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); - return needGenerate; - } - - private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) { - return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, - boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); - if (generated.isRight()) { - return generated; - } - byte[] decodedPayload = artifactDefinition.getPayloadData(); - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload)); - return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null, - shouldLock, inTransaction); - - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { - log.debug("tosca artifact generation"); - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { - Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); - - if (generated.isRight()) { - log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value()); - - return Either.right(generated.right().value()); - } - byte[] value = generated.left().value(); - artifactInfo.setPayload(value); - - } else { - Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent); - if (exportComponent.isRight()) { - log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value()); - ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status); - return Either.right(responseFormat); - } - log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); - String payload = exportComponent.left().value().getMainYaml(); - artifactInfo.setPayloadData(payload); - } - return Either.left(Either.left(artifactInfo)); - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, - String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - if (interfaceName != null && operationName != null) { - interfaceName = interfaceName.toLowerCase(); - operationName = operationName.toLowerCase(); - } - switch (operation.getArtifactOperationEnum()) { - case Download: - if (artifactGenerationRequired(parent, artifactInfo)) { - return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction); - } - return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); - case Delete: - return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction); - case Update: - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null; - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) - && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { - result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either<ArtifactDefinition, Operation> updateResult = result.left().value(); - ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } - } - } else { - if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { - result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup); - } - } - if (result == null) { - result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either<ArtifactDefinition, Operation> updateResult = result.left().value(); - - ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } - } - } - return result; - case Create: - return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - case Link: - return handleLink(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - } - return null; - } - - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) { - List<GroupDefinition> groups = parent.getGroups(); - if (groups != null && !groups.isEmpty()) { - List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList()); - if (groupToUpdate != null && !groupToUpdate.isEmpty()) { - groupToUpdate.forEach(g -> { - g.getArtifacts().remove(artifactInfo.getUniqueId()); - g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID()); - g.getArtifacts().add(artAfterUpdate.getUniqueId()); - g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); - }); - Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - } - } - return ActionStatus.OK; - } - - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) { - List<GroupDefinition> groups = parent.getGroups(); - if (groups != null && !groups.isEmpty()) { - List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList()); - if (groupToUpdate != null && !groupToUpdate.isEmpty()) { - groupToUpdate.forEach(g -> { - g.getArtifacts().remove(artifactInfoHeat.getUniqueId()); - g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID()); - g.getArtifacts().remove(artifactInfoHeatE.getUniqueId()); - g.getArtifacts().add(artHeatAfterUpdate.getUniqueId()); - g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID()); - g.getArtifacts().add(artHEAfterUpdate.getUniqueId()); - }); - Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - } - } - return ActionStatus.OK; - } - - private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) { - List<GroupInstance> updatedGroupInstances = new ArrayList<>(); - List<GroupInstance> groupInstances = null; - Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst(); - if (componentInstOp.isPresent()) { - groupInstances = componentInstOp.get().getGroupInstances(); - } - if (CollectionUtils.isNotEmpty(groupInstances)) { - boolean isUpdated = false; - for (GroupInstance groupInstance : groupInstances) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) { - groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId()); - groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId()); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) { - groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); - groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroupInstances.add(groupInstance); - } - } - } - Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - return ActionStatus.OK; - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; - if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { - result = generateToscaArtifact(parent, artifactInfo, false, false); - } else { - String heatArtifactId = artifactInfo.getGeneratedFromId(); - Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); - if (heatRes.isRight()) { - log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), ""); - return Either.right(responseFormat); - } - String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); - artifactInfo.setPayloadData(generatedPayload); - result = Either.left(Either.left(artifactInfo)); - } - return result; - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); - Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId()); - ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); - - if (origMd5 != null) { - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - - Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup); - return resultOp; - - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - if (false == inTransaction) - titanDao.rollback(); - } else { - log.debug("all changes committed"); - if (false == inTransaction) - titanDao.commit(); - } - if (shouldLock) - componentType = parent.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - } - - public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { - if (artifactGenerationRequired(component, csarArtifact)) { - Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false); - - if (generated.isRight()) { - log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value()); - - return Either.right(generated.right().value()); - } - return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value())); - } - return downloadArtifact(csarArtifact, component); - } - - public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { - // perform all validation in common flow - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null, - null, parentId, containerComponentType); - if (result.isRight()) { - return Either.right(result.right().value()); - } - ArtifactDefinition artifactDefinition; - Either<ArtifactDefinition, Operation> insideValue = result.left().value(); - if (insideValue.isLeft()) { - artifactDefinition = insideValue.left().value(); - } else { - artifactDefinition = insideValue.right().value().getImplementationArtifact(); - } - // for tosca artifacts and heat env on VF level generated on download without saving - if (artifactDefinition.getPayloadData() != null) { - return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData())); - } - return downloadArtifact(artifactDefinition, null); - } - - public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { - // step 1 - // detect auditing type - Map<String, ArtifactDefinition> resMap = null; - Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null; - - new Wrapper<>(); - // step 2 - // check header - if (userId == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); - - resultOp = Either.right(responseFormat); - return resultOp; - } - // step 3 - // check user existence - // step 4 - // check user's role - - Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false); - if (userResult.isRight()) { - - resultOp = Either.right(userResult.right().value()); - return resultOp; - } - - userResult.left().value(); - - // steps 5 - 6 - 7 - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - // ComponentInstance resourceInstance = null; - String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - ComponentParametersView componentFilter = new ComponentParametersView(); - componentFilter.disableAll(); - componentFilter.setIgnoreArtifacts(false); - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) - componentFilter.setIgnoreComponentInstances(false); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false); - - if (validateComponent.isRight()) { - resultOp = Either.right(validateComponent.right().value()); - return resultOp; - } - component = validateComponent.left().value(); - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock "); - if (lockComponent.isRight()) { - - resultOp = Either.right(lockComponent.right().value()); - return resultOp; - } - - try { - ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); - - if (groupType == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - - resultOp = Either.right(responseFormat); - return resultOp; - - } - if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { - List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); - if (list != null && !list.isEmpty()) { - resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); - } else { - resMap = new HashMap<>(); - } - resultOp = Either.left(resMap); - return resultOp; - } else { - - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId); - if (artifactsMapStatus.isRight()) { - if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - resultOp = Either.right(responseFormat); - } else { - resMap = new HashMap<>(); - resultOp = Either.left(resMap); - } - } else { - resMap = artifactsMapStatus.left().value(); - resultOp = Either.left(resMap); - } - return resultOp; - } - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - titanDao.rollback(); - } else { - log.debug("all changes committed"); - - titanDao.commit(); - } - - componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - - } - - private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId, - boolean inTransaction) { - // step 9 - // check artifact existence - Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId()); - if (artifactResult.isRight()) { - if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - log.debug("addArtifact - artifact {} not found", artifactId); - return Either.right(responseFormat); - - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value())); - log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value()); - return Either.right(responseFormat); - } - } - // step 9.1 - // check artifact belong to component - boolean found = false; - switch (componentType) { - case RESOURCE: - case SERVICE: - found = checkArtifactInComponent(component, artifactId); - break; - case RESOURCE_INSTANCE: - found = checkArtifactInResourceInstance(component, componentId, artifactId); - break; - default: - - } - if (!found) { - // String component = - // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" : - // "service"; - String componentName = componentType.name().toLowerCase(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName); - log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId); - return Either.right(responseFormat); - } - return Either.left(artifactResult.left().value()); - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - String artifactId = null; - - // step 11 - Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction); - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - convertParentType(componentType); - - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - - try { - resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName); - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - - } - - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - - try { - resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - - } - - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - convertParentType(componentType); - - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); - - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName); - return resultOp; - - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction); - - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - - return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); - } - - private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) { - // Md5 validations - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - // step 11 - Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction); - if (validateResult.isRight()) { - ResponseFormat responseFormat = validateResult.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(validateResult.right().value()); - } - - Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - log.debug("Error during handle payload"); - return Either.right(responseFormat); - } - - // validate heat parameters. this part must be after the parameters are - // extracted in "handlePayload" - Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType()); - if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); - handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); - log.debug("Error during handle payload"); - return Either.right(responseFormat); - } - return payloadEither; - } - - public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, - ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { - - if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { - return; - } - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid); - - if (user == null) { - user = new User(); - user.setUserId("UNKNOWN"); - } - switch (componentTypeEnum) { - - case RESOURCE: - Resource resource = (Resource) component; - if (resource == null) { - // In that case, component ID should be instead of name - resource = new Resource(); - resource.setName(componentId); - } - componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields); - break; - - case SERVICE: - Service service = (Service) component; - if (service == null) { - // In that case, component ID should be instead of name - service = new Service(); - service.setName(componentId); - } - componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields); - break; - - case RESOURCE_INSTANCE: - if (resourceInstanceName == null) { - resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields); - - break; - default: - break; - } - } - - private String getResourceInstanceNameFromComponent(Component component, String componentId) { - ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null); - String resourceInstanceName = null; - if (resourceInstance != null) { - resourceInstanceName = resourceInstance.getName(); - } - return resourceInstanceName; - } - - public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - // Putting together artifact info - String artifactData = buildAuditingArtifactData(artifactDefinition); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid); - return auditingFields; - } - - // ----- - - private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) { - StringBuilder sb = new StringBuilder(); - if (artifactDefinition != null) { - sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",") - .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId()); - - sb.append(","); - if (artifactDefinition.getArtifactVersion() != null) { - - sb.append(artifactDefinition.getArtifactVersion()); - } else { - sb.append(" "); - } - sb.append(","); - if (artifactDefinition.getArtifactUUID() != null) { - sb.append(artifactDefinition.getArtifactUUID()); - } else { - sb.append(" "); - } - } - return sb.toString(); - } - - private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { - - if (origMd5 != null) { - String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData); - - if (false == encodeBase64Str.equals(origMd5)) { - log.debug("The calculated md5 is different then the received one"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - } else { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - if (payload!=null && payload.length != 0) { - log.debug("Missing md5 header during artifact create"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - } - // Update metadata - if (payload != null && payload.length != 0) { - log.debug("Cannot have payload while md5 header is missing"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - return Either.left(true); - } - - private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, - ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) { - - Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); - if (artifactById.isRight()) { - return Either.right(artifactById.right().value()); - } - ArtifactDefinition currentArtifactInfo = artifactById.left().value(); - - ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo); - Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); - if (validateInformationalArtifactRes.isRight()) { - return Either.right(validateInformationalArtifactRes.right().value()); - } - Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); - if (validateAndSetArtifactname.isRight()) { - return Either.right(validateAndSetArtifactname.right().value()); - } - if (operationName != null && interfaceName != null) { - operationName = operationName.toLowerCase(); - interfaceName = interfaceName.toLowerCase(); - } - Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType); - if (logicalNameStatus.isRight()) { - return Either.right(logicalNameStatus.right().value()); - } - // This is a patch to block possibility of updating service api fields - // through other artifacts flow - - if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); - } else { - checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); - } - - composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName); - if (currentArtifactInfo != null) { - artifactInfo.setMandatory(currentArtifactInfo.getMandatory()); - } - - // artifactGroupType is not allowed to be updated - if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); - if (validateGroupType.isRight()) { - return Either.right(validateGroupType.right().value()); - } - } - // TODO TEMP !!! - NodeTypeEnum parentType = convertParentType(componentType); - - // TODO TEMP !!! - boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); - - if (isDeploymentArtifact(artifactInfo)) { - Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType); - if (deploymentValidationResult.isRight()) { - return Either.right(deploymentValidationResult.right().value()); - } - } else { - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - - /* - * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo, - * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } } - */ - } - - Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo); - if (descriptionResult.isRight()) { - return Either.right(descriptionResult.right().value()); - } - - if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) { - Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType); - if (validateServiceApiType.isRight()) { - return Either.right(validateServiceApiType.right().value()); - } - // Change of type is not allowed and should be ignored - - artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER); - - Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo); - if (validateUrl.isRight()) { - return Either.right(validateUrl.right().value()); - } - - Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo); - if (validateUpdate.isRight()) { - log.debug("serviceApi first update cnnot be without payload."); - return Either.right(validateUpdate.right().value()); - } - } else { - Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType); - if (validateArtifactType.isRight()) { - return Either.right(validateArtifactType.right().value()); - } - if (artifactInfo.getApiUrl() != null) { - artifactInfo.setApiUrl(null); - log.error("Artifact URL cannot be set through this API - ignoring"); - } - - if (artifactInfo.getServiceApi() != null) { - if (artifactInfo.getServiceApi()) { - artifactInfo.setServiceApi(false); - log.error("Artifact service API flag cannot be changed - ignoring"); - } - } - } - - return Either.left(artifactInfo); - } - - private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) { - if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){ - artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); - artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType()); - artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel()); - } - } - - private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { - - Either<ArtifactDefinition, ResponseFormat> result = null; - ArtifactDefinition foundArtifact = null; - if (StringUtils.isNotEmpty(artifactId)) { - foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); - } - if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - log.debug("Artifact {} already exist", artifactId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); - } - if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); - } - if (result == null) { - result = Either.left(foundArtifact); - } - return result; - } - - private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { - ArtifactDefinition foundArtifact; - if (parentComponent.getUniqueId().equals(parentId)) { - foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); - } else { - ComponentInstance instance = findComponentInstance(parentId, parentComponent); - foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); - } - return foundArtifact; - } - - private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { - ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - Either<Boolean, ResponseFormat> validationResult = Either.left(true); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (artifactType == null) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { - String artifactTypeName = artifactType.getType(); - ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); - Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts(); - Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet(); - if (!validArtifactTypes.contains(artifactTypeName)) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); - } else { - List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes(); - if (!validResourceType.contains(parentResourceType.name())) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); - } - } - } - return validationResult; - } - - private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - return NodeTypeEnum.Resource; - } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { - return NodeTypeEnum.ResourceInstance; - } else { - return NodeTypeEnum.Service; - } - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, - String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - NodeTypeEnum parentType = convertParentType(componentType); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null; - ArtifactDefinition foundArtifact = null; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null; - org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; - boolean isDuplicated = false; - String esId = null; - Either<Boolean, StorageOperationStatus> needCloneRes = null; - try { - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - resultOp = Either.right(lockComponent.right().value()); - } - } - if (resultOp == null) { - log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); - getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - if (resultOp == null) { - fetchedContainerComponent = getContainerRes.left().value(); - log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); - getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); - if (getArtifactRes.isRight()) { - log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } else { - foundArtifact = getArtifactRes.left().value().getLeft(); - esId = foundArtifact.getEsId(); - } - } - if (resultOp == null && StringUtils.isNotEmpty(esId)) { - needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType())); - if (needCloneRes.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - boolean isNeedToDeleteArtifactFromDB = true; - if (resultOp == null) { - - if(componentType == ComponentTypeEnum.RESOURCE_INSTANCE){ - String instanceId = parentId; - Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); - - if (isOnlyResourceInstanceArtifact.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right().value(), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); - } - - Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value()); - if (updatedArtifactRes.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } else { - isDuplicated = updatedArtifactRes.left().value().getDuplicated(); - } - } - - if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) { - - if(isNeedToDeleteArtifactFromDB){ - log.debug("Going to delete the artifact {} from the database. ", artifactId); - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); - if (cassandraStatus != CassandraOperationStatus.OK) { - log.debug("Failed to delete the artifact {} from the database. ", artifactId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - - List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances()); - if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { - List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups()); - if (CollectionUtils.isNotEmpty(updatedGroups)) { - Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null) { - resultOp = Either.left(Either.left(foundArtifact)); - handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); - } - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - } - } - - private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact( ArtifactDefinition foundArtifact, Component parent, String instanceId) { - Either<Boolean, ActionStatus> result = Either.left(true); - ComponentInstance foundInstance = null; - Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if (!componentInstanceOpt.isPresent()) { - result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); - } else { - foundInstance = componentInstanceOpt.get(); - String componentUid = foundInstance.getComponentUid(); - Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", componentUid); - result = Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); - } - Component origComponent = getContainerRes.left().value(); - Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts(); - if( deploymentArtifacts!= null && !deploymentArtifacts.isEmpty()){ - Optional<String> op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); - if(op.isPresent()){ - return Either.left(false); - } - } - Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts(); - if( artifacts!= null && !artifacts.isEmpty()){ - Optional<String> op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); - if(op.isPresent()){ - return Either.left(false); - } - } - - } - return result; - } - - private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) { - List<GroupDataDefinition> updatedGroups = new ArrayList<>(); - boolean isUpdated = false; - if (groups != null) { - for (GroupDefinition group : groups) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) { - group.getArtifacts().remove(artifactId); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroups.add(group); - } - } - } - return updatedGroups; - } - - private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) { - List<GroupInstance> updatedGroupInstances = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(groupInstances)) { - boolean isUpdated = false; - for (GroupInstance groupInstance : groupInstances) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) { - groupInstance.getGroupInstanceArtifacts().remove(artifactId); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroupInstances.add(groupInstance); - } - } - } - return updatedGroupInstances; - } - - private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { - - Either<ArtifactDataDefinition, StorageOperationStatus> result; - boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); - String componentId = component.getUniqueId(); - String instanceId = componentId.equals(parentId) ? null : parentId; - if (isMandatory) { - log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); - resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); - } else if (cloneIsNeeded) { - log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); - result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); - } else { - log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); - result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); - } - return result; - } - - private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { - - Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null; - Map<String, ArtifactDefinition> artifacts = new HashMap<>(); - ComponentInstance foundInstance = null; - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { - Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst(); - if (!componentInstanceOpt.isPresent()) { - result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); - } else { - foundInstance = componentInstanceOpt.get(); - fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); - } - } else { - fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); - } - if (result == null) { - if (artifacts.containsKey(artifactId)) { - result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); - } else { - result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); - } - } - return result; - } - - private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) { - Map<String, ArtifactDefinition> currArtifacts; - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { - currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { - currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { - currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - } - - private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) { - Map<String, ArtifactDefinition> currArtifacts; - if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { - currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { - currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - } - - private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { - StorageOperationStatus result; - switch (cassandraStatus) { - case OK: - result = StorageOperationStatus.OK; - break; - case NOT_FOUND: - result = StorageOperationStatus.NOT_FOUND; - break; - case CLUSTER_NOT_CONNECTED: - case KEYSPACE_NOT_CONNECTED: - result = StorageOperationStatus.CONNECTION_FAILURE; - break; - default: - result = StorageOperationStatus.GENERAL_ERROR; - break; - } - return result; - } - - private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { - if (fetchedArtifact != null) { - log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); - fetchedArtifact.setEsId(null); - fetchedArtifact.setArtifactName(null); - fetchedArtifact.setDescription(null); - fetchedArtifact.setApiUrl(null); - fetchedArtifact.setArtifactChecksum(null); - nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact); - fetchedArtifact.setArtifactUUID(null); - long time = System.currentTimeMillis(); - fetchedArtifact.setPayloadUpdateDate(time); - fetchedArtifact.setHeatParameters(null); - fetchedArtifact.setHeatParamsUpdateDate(null); - } - } - - private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) { - StorageOperationStatus error = StorageOperationStatus.OK; - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - log.debug("Need to re-generate customization UUID for instance {}", instanceId); - error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId); - } - return error; - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) { - Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId()); - if (artifactById.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); - log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - ArtifactDefinition artifactDefinition = artifactById.left().value(); - if (artifactDefinition == null) { - log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); - return Either.left(insideEither); - } - - private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) { - Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId); - if (!(ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) && artifactById.isRight()) { - // in case of update artifact must be - BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); - log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); - } - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && artifactById.isLeft()) { - log.debug("Artifact {} already exist", artifactId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); - } - ArtifactDefinition currentArtifactInfo = null; - if (artifactById.isLeft()) { - // get previous value - currentArtifactInfo = artifactById.left().value(); - } - return Either.left(currentArtifactInfo); - } - - private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, - ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) { - - String artifactLabel = artifactInfo.getArtifactLabel(); - if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) { - BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); - log.debug("missing artifact logical name for component {}", componentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) { - - if (operationName != null) { - if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { - log.debug("artifact label cannot be set {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); - } else { - artifactLabel = operationName; - } - } - String displayName = artifactInfo.getArtifactDisplayName(); - if (displayName == null || displayName.isEmpty()) - displayName = artifactLabel; - displayName = ValidationUtils.cleanArtifactDisplayName(displayName); - // if (!ValidationUtils.validateArtifactDisplayName(displayName)) { - // log.debug("Invalid format form Artifact displayName : {}", displayName); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - // } - artifactInfo.setArtifactDisplayName(displayName); - - if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { - log.debug("Invalid format form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel); - - if (artifactLabel.isEmpty()) { - log.debug("missing normalized artifact logical name for component {}", componentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - - if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) { - log.debug("Invalid lenght form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); - } - if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) { - log.debug("Non unique Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); - } - } - artifactInfo.setArtifactLabel(artifactLabel); - - return Either.left(ActionStatus.OK); - } - - private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) { - boolean isUnique = true; - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts; - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { - artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); - } else { - artifacts = artifactToscaOperation.getArtifacts(componentId); - } - - if (artifacts.isLeft()) { - for (String label : artifacts.left().value().keySet()) { - if (label.equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true); - if (allInterfacesOfResource.isLeft()) { - for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { - for (Operation operation : interace.getOperationsMap().values()) { - if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - } - } - return isUnique; - } - - // *************************************************************** - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - ComponentInstance foundInstance = findComponentInstance(parentId, parent); - String instanceId = null; - String instanceName = null; - if (foundInstance != null) { - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); - NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - result.left().value(); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } if (isLeft) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; - } else{ - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; - - } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { - - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - ComponentInstance foundInstance = findComponentInstance(parentId, parent); - String instanceId = null; - String instanceName = null; - if (foundInstance != null) { - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - if (artifactData == null) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug("Failed to create artifact object for ES."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); - resultOp = Either.right(responseFormat); - return resultOp; - - } - // set on graph object id of artifact in ES! - artifactInfo.setEsId(artifactData.getId()); - - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; - if (interfaceType != null && operationName != null) { - // lifecycle artifact - Operation operation = convertToOperation(artifactInfo, operationName); - - Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getImplementation().getUniqueId(); - result.left().value().getImplementation(); - - insideEither = Either.right(result.left().value()); - resultOp = Either.left(insideEither); - } else { - error = result.right().value(); - } - } else { - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); - NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - result.left().value(); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } else { - error = result.right().value(); - } - } - if (isLeft) { - boolean res = saveArtifacts(artifactData, parentId, false); - // String uniqueId = artifactDefinition.getUniqueId(); - - if (res) { - log.debug("Artifact saved into ES - {}", artifactUniqueId); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - - resultOp = Either.right(responseFormat); - return resultOp; - } - } else { - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; - } - - } - - private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { - ComponentInstance foundInstance = null; - if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { - foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); - } - return foundInstance; - } - - private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { - - Either<Boolean, ResponseFormat> result = Either.left(true); - Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>(); - - validateArtifactTypeExists(responseWrapper, artifactInfo); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - - Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); - - if (responseWrapper.isEmpty()) { - validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); - } - - if (responseWrapper.isEmpty()) { - // Common code for all types - // not allowed to change artifactType - if (!isCreate) { - Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact); - if (validateServiceApiType.isRight()) { - responseWrapper.setInnerElement(validateServiceApiType.right().value()); - } - } - } - if (responseWrapper.isEmpty()) { - if (parentType.equals(NodeTypeEnum.Resource)) { - // if (parentComponent instanceof Resource) { - Resource resource = (Resource) parentComponent; - ResourceTypeEnum resourceType = resource.getResourceType(); - ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); - if (config == null) { - responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } else { - List<String> myList = config.getValidForResourceTypes(); - Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList); - if (either.isRight()) { - responseWrapper.setInnerElement(either.right().value()); - } - } - } - } - if (responseWrapper.isEmpty()) { - validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); - } - - if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) { - String artifactName = artifactInfo.getArtifactName(); - if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) { - validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType); - } - } - - if (responseWrapper.isEmpty()) { - switch (artifactType) { - case HEAT: - case HEAT_VOL: - case HEAT_NET: { - result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType); - break; - } - case HEAT_ENV: { - result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType); - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - break; - } - case DCAE_INVENTORY_TOSCA: - case DCAE_INVENTORY_JSON: - case DCAE_INVENTORY_POLICY: - // Validation is done in handle payload. - case DCAE_INVENTORY_DOC: - case DCAE_INVENTORY_BLUEPRINT: - case DCAE_INVENTORY_EVENT: - // No specific validation - default: { - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - } - } - - } - - if (!responseWrapper.isEmpty()) { - result = Either.right(responseWrapper.getInnerElement()); - } - return result; - } - - private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) { - if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); - } - } - - private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { - Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null; - if (parentType.equals(NodeTypeEnum.Resource)) { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - } else { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } - return resourceDeploymentArtifacts; - } - - public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) { - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (artifactType == null) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); - } - } - - private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - ArtifactTypeConfig retConfig = null; - String fileType = artifactType.getType(); - if (parentType.equals(NodeTypeEnum.Resource)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType); - } else if (parentType.equals(NodeTypeEnum.Service)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType); - } - return retConfig; - } - - private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) { - // extract heat parameters - if (artifactInfo.getPayloadData() != null) { - String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType()); - if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { - log.info("failed to parse heat parameters "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType()); - return Either.right(responseFormat); - } else if (heatParameters.isLeft() && heatParameters.left().value() != null) { - artifactInfo.setListHeatParameters(heatParameters.left().value()); - } - } - return Either.left(true); - - } - - // Valid extension - public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - String fileType = artifactType.getType(); - List<String> acceptedTypes = null; - ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); - if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { - log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return; - } - - if (deploymentAcceptedTypes == null) { - log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - return; - } else { - acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); - } - /* - * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. - * - * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}", - * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType : - * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError( - * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; } - */ - - String artifactName = artifactInfo.getArtifactName(); - String fileExtension = GeneralUtility.getFilenameExtension(artifactName); - // Pavel - File extension validation is case-insensitive - Ella, - // 21/02/2016 - if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) { - log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType)); - return; - } - } - - private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - - Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>(); - Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>(); - Wrapper<byte[]> payloadWrapper = new Wrapper<>(); - - if (errorWrapper.isEmpty()) { - validateValidYaml(errorWrapper, artifactInfo); - } - - if (errorWrapper.isEmpty()) { - // Validate Heat Exist - validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType()); - } - - // if (errorWrapper.isEmpty() && isCreate) { - // // Validate Only Single HeatEnv Artifact - // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId); - // } - - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); - } - - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); - } - - // Init Response - Either<Boolean, ResponseFormat> eitherResponse; - if (errorWrapper.isEmpty()) { - eitherResponse = Either.left(true); - } else { - eitherResponse = Either.right(errorWrapper.getInnerElement()); - } - return eitherResponse; - } - - public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) { - if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) { - Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition); - if (fillArtifactPayload.isRight()) { - errorWrapper.setInnerElement(fillArtifactPayload.right().value()); - log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); - } - } else { - payloadWrapper.setInnerElement(artifactDefinition.getPayloadData()); - } - } - - public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) { - Either<Boolean, ResponseFormat> result = Either.left(true); - Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId()); - if (eitherArtifactData.isLeft()) { - byte[] data = eitherArtifactData.left().value().getDataAsArray(); - data = Base64.encodeBase64(data); - payloadWrapper.setInnerElement(data); - } else { - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); - result = Either.right(responseFormat); - } - return result; - - } - - @SuppressWarnings("unchecked") - private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { - String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); - Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload); - String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); - Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload); - - Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS); - Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS); - if (eitherHeatEnvProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); - errorWrapper.setInnerElement(responseFormat); - log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); - } else if (eitherHeatProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - } else { - Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); - Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); - heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); - if (heatEnvPropertiesKeys.size() > 0) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - } - } - } - - private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) { - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); - if (!isYamlValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType()); - errorWrapper.setInnerElement(responseFormat); - log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName()); - } - } - - public boolean isValidXml(byte[] xmlToParse) { - if(parser == null) { - log.debug("SAX XML Parser have not been initialized"); - return false; - } - boolean isXmlValid = true; - - try { - parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse))); - } catch (IOException | SAXException e) { - log.debug("Xml is invalid : {}", e.getMessage(), e); - isXmlValid = false; - } - - return isXmlValid; - } - - public boolean isValidJson(byte[] jsonToParse) { - String parsed = new String(jsonToParse); - try { - gson.fromJson(parsed, Object.class); - } catch (Exception e) { - log.debug("Json is invalid : {}", e.getMessage(), e); - return false; - } - return true; - } - - public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) { - boolean typeArtifactFound = false; - // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = - // (parentType == NodeTypeEnum.Resource) ? - // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource) - // parentComponent).iterator() - // : getDeploymentArtifacts(parentComponent, parentType).iterator(); - - Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator(); - - while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) { - ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType()); - typeArtifactFound = (foundArtifactType == allowedArtifactType); - } - if (typeArtifactFound) { - String parentName = parentComponent.getName(); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType()); - - errorWrapper.setInnerElement(responseFormat); - log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType()); - - } - } - - public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) { - boolean artifactNameFound = false; - // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = - // (parentType == NodeTypeEnum.Resource) ? - // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource) - // parentComponent).iterator() - // : getDeploymentArtifacts(parentComponent, parentType).iterator(); - - Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator(); - - while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) { - artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName())); - } - if (artifactNameFound) { - String parentName = parentComponent.getName(); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName); - - errorWrapper.setInnerElement(responseFormat); - log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); - - } - } - - private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, - ComponentTypeEnum componentType) { - Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); - if (res.isRight()) { - ResponseFormat responseFormat; - if (res.right().value() == StorageOperationStatus.NOT_FOUND) { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } else { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } - errorWrapper.setInnerElement(responseFormat); - - return; - } - ArtifactDefinition heatArtifact = res.left().value(); - heatArtifactMDWrapper.setInnerElement(heatArtifact); - // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator(); - // while (!heatFound && parentArtifactsItr.hasNext()) { - // ArtifactDefinition currArtifact = parentArtifactsItr.next(); - // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) { - // heatFound = true; - // heatArtifactMDWrapper.setInnerElement(currArtifact); - // log.trace("In validateHeatExist found artifact {}", currArtifact); - // /* - // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){ - // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); } - // */ - // } - // } - // if (!heatFound) { - // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - // errorWrapper.setInnerElement(responseFormat); - // log.debug("Can't create heat env artifact because No heat Artifact exist."); - // } - - } - - private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { - log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); - // timeout > 0 for HEAT artifacts - Integer timeout = artifactInfo.getTimeout(); - Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout(); - if (timeout == null) { - artifactInfo.setTimeout(defaultTimeout); - // HEAT artifact but timeout is invalid - } else if (timeout < 1) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT)); - } - - // US649856 - Allow several HEAT files on Resource - /* - * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return - * Either.right(errorWrapper.getInnerElement()); } } - */ - - log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel()); - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) { - String listToString = (typeList != null) ? typeList.toString() : ""; - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue()); - Either<Boolean, ResponseFormat> either = Either.right(responseFormat); - String resourceTypeName = resourceType.name(); - if (typeList != null && typeList.contains(resourceTypeName)) { - either = Either.left(true); - } - return either; - } - - private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { - if (artifactInfo.getHeatParameters() != null) { - for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { - String parameterType = heatParam.getType(); - HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType); - String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType(); - if (heatParameterType == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType()); - return Either.right(responseFormat); - } - - StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty); - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName()); - return Either.right(responseFormat); - } - } - } - return Either.left(artifactInfo); - } - - public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) { - List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>(); - if (parentComponent.getDeploymentArtifacts() != null) { - if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) { - Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null); - if (getRI.isRight()) { - return deploymentArtifacts; - } - ComponentInstance ri = getRI.left().value(); - if (ri.getDeploymentArtifacts() != null) { - deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); - } - } else if (parentComponent.getDeploymentArtifacts() != null) { - deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); - } - } - return deploymentArtifacts; - } - - private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) { - // on create if null add informational to current - if (artifactInfo.getArtifactGroupType() == null) { - artifactInfo.setArtifactGroupType(type); - } - if (artifactInfo.getUniqueId() != null) { - log.error("artifact uniqid cannot be set ignoring"); - } - artifactInfo.setUniqueId(null); - - if (artifactInfo.getArtifactRef() != null) { - log.error("artifact ref cannot be set ignoring"); - } - artifactInfo.setArtifactRef(null); - - if (artifactInfo.getArtifactRepository() != null) { - log.error("artifact repository cannot be set ignoring"); - } - artifactInfo.setArtifactRepository(null); - - if (artifactInfo.getUserIdCreator() != null) { - log.error("creator uuid cannot be set ignoring"); - } - artifactInfo.setArtifactCreator(user.getUserId()); - - if (artifactInfo.getUserIdLastUpdater() != null) { - log.error("userId of last updater cannot be set ignoring"); - } - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - if (artifactInfo.getCreatorFullName() != null) { - log.error("creator Full name cannot be set ignoring"); - } - String fullName = user.getFirstName() + " " + user.getLastName(); - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getUpdaterFullName() != null) { - log.error("updater Full name cannot be set ignoring"); - } - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getCreationDate() != null) { - log.error("Creation Date cannot be set ignoring"); - } - long time = System.currentTimeMillis(); - artifactInfo.setCreationDate(time); - - if (artifactInfo.getLastUpdateDate() != null) { - log.error("Last Update Date cannot be set ignoring"); - } - artifactInfo.setLastUpdateDate(time); - - if (artifactInfo.getEsId() != null) { - log.error("es id cannot be set ignoring"); - } - artifactInfo.setEsId(null); - - } - - /* - * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate - * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId); - * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return - * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return - * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value - * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); } - */ - - private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) { - String id = artifactId; - if (artifactId == null || artifactId.isEmpty()) { - String uniqueId = null; - if (interfaceName != null && operationName != null) { - uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel()); - } else { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()); - } - artifactInfo.setUniqueId(uniqueId); - artifactInfo.setEsId(uniqueId); - id = uniqueId; - } else { - artifactInfo.setUniqueId(artifactId); - artifactInfo.setEsId(artifactId); - } - return id; - } - - private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { - BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); - log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); - } - - boolean artifactTypeExist = false; - Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null; - ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); - - if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { - allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType); - } else { - - allArtifactTypes = elementOperation.getAllArtifactTypes(); - } - if (allArtifactTypes.isRight()) { - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); - log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value()); - return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); - } - - for (ArtifactType type : allArtifactTypes.left().value()) { - if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) { - artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase()); - artifactTypeExist = true; - break; - } - } - - if (!artifactTypeExist) { - BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); - log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } - - return Either.left(ActionStatus.OK); - } - - private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - - Map<String, ArtifactTypeConfig> deploymentArtifacts = null; - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - - if (parentType.equals(NodeTypeEnum.Service)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - } else { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } - if (deploymentArtifacts != null) { - for (String artifactType : deploymentArtifacts.keySet()) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return Either.left(artifactTypes); - } else { - return Either.right(ActionStatus.GENERAL_ERROR); - } - - } - - private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD)); - } - return Either.left(true); - - } - - private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) { - if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); - } - - String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName()); - if (normalizeFileName == null || normalizeFileName.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); - } - artifactInfo.setArtifactName(normalizeFileName); - - if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH))); - } - - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { - log.info("artifact type is missing operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); - } - - if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { - log.info("artifact type cannot be changed operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(true); - } - - private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactGroupType() == null) { - artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - } - - else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { - log.info("artifact group type cannot be changed. operation failed"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(artifactInfo); - } - - private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) { - - // on update if null add informational to current - if (currentArtifact.getArtifactGroupType() == null && type != null) { - currentArtifact.setArtifactGroupType(type); - } - - if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) { - log.error("artifact uniqid cannot be set ignoring"); - } - artifactInfo.setUniqueId(currentArtifact.getUniqueId()); - - if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) { - log.error("artifact ref cannot be set ignoring"); - } - artifactInfo.setArtifactRef(currentArtifact.getArtifactRef()); - - if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) { - log.error("artifact repository cannot be set ignoring"); - } - artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository()); - - if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) { - log.error("creator uuid cannot be set ignoring"); - } - artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator()); - - if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) { - log.error("artifact creator cannot be set ignoring"); - } - artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator()); - - if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) { - log.error("userId of last updater cannot be set ignoring"); - } - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) { - log.error("creator Full name cannot be set ignoring"); - } - artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName()); - - if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) { - log.error("updater Full name cannot be set ignoring"); - } - String fullName = user.getFirstName() + " " + user.getLastName(); - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) { - log.error("Creation Date cannot be set ignoring"); - } - artifactInfo.setCreationDate(currentArtifact.getCreationDate()); - - if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) { - log.error("Last Update Date cannot be set ignoring"); - } - long time = System.currentTimeMillis(); - artifactInfo.setLastUpdateDate(time); - - if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) { - log.error("es id cannot be set ignoring"); - } - artifactInfo.setEsId(currentArtifact.getUniqueId()); - - if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) { - log.error(" Artifact Display Name cannot be set ignoring"); - } - artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName()); - - if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) { - log.debug("serviceApi cannot be set. ignoring."); - } - artifactInfo.setServiceApi(currentArtifact.getServiceApi()); - - if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) { - log.debug("artifact group cannot be set. ignoring."); - } - artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - - artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion()); - - if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) { - log.debug("artifact UUID cannot be set. ignoring."); - } - artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); - - if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) { - checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters()); - } - } - - private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) { - - Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters); - for (HeatParameterDefinition parameter : heatParameters) { - HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId()); - - if (currentParam != null) { - - if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) { - log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName()); - parameter.setName(currentParam.getName()); - } - if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) { - log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); - parameter.setDefaultValue(currentParam.getDefaultValue()); - } - if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) { - log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType()); - parameter.setType(currentParam.getType()); - } - if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) { - log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription()); - parameter.setDescription(currentParam.getDescription()); - } - - // check and set current value - if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) { - log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue()); - parameter.setCurrentValue(currentParam.getDefaultValue()); - } - } - } - } - - private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) { - - Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>(); - for (HeatParameterDefinition param : currentParameters) { - currentParamsMap.put(param.getUniqueId(), param); - } - return currentParamsMap; - } - - private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) { - if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) { - log.debug("Artifact url cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL)); - } - artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase()); - - if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL)); - } - if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH))); - } - - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) { - if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) { - log.debug("Artifact description cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION)); - } - String description = artifactInfo.getDescription(); - description = ValidationUtils.removeNoneUtf8Chars(description); - description = ValidationUtils.normaliseWhitespace(description); - description = ValidationUtils.stripOctets(description); - description = ValidationUtils.removeHtmlTagsOnly(description); - if (!ValidationUtils.validateIsEnglish(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH))); - } - artifactInfo.setDescription(description); - return Either.left(true); - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload, - ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) { - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - String prevArtifactId = null; - String currArtifactId = artifactId; - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - - if (artifactData == null) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to create artifact object for ES."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - log.trace("Try to update entry on graph"); - String artifactUniqueId = null; - ArtifactDefinition artifactDefinition = artifactInfo; - StorageOperationStatus error = null; - - boolean isLeft = false; - if (interfaceType != null && operationName != null) { - // lifecycle artifact - /* - * Operation operation = convertToOperation(artifactInfo, operationName); - * - * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); - * - * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation(); - * - * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); } - */ - } else { - log.debug("Enty on graph is updated. Update artifact in ES"); - boolean res = true; - // Changing previous and current artifactId for auditing - prevArtifactId = currArtifactId; - currArtifactId = artifactDefinition.getUniqueId(); - - NodeTypeEnum convertParentType = convertParentType(componentType); - - if (decodedPayload == null) { - if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { - Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId()); - // Either<ESArtifactData, ResourceUploadStatus> - // artifactfromES = daoUploader.getArtifact(artifactId); - if (artifactFromCassandra.isRight()) { - log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); - error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - // clone data to new artifact - artifactData.setData(artifactFromCassandra.left().value().getData()); - artifactData.setId(artifactFromCassandra.left().value().getId()); - } - } else { - if (artifactDefinition.getEsId() == null) { - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactData.setId(artifactDefinition.getUniqueId()); - } - } - - Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId); - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - artifactDefinition = result.left().value(); - String artifactType = artifactInfo.getArtifactType(); - if (NodeTypeEnum.Resource == convertParentType - && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) { - - if (!artifactUniqueId.equals(artifactId)) { - // need to update the generated id in heat env - Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts(); - Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst(); - if (findFirst.isPresent()) { - ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); - artifactEnvInfo.setArtifactChecksum(null); - artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId); - } - } - - /* - * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType); - * - * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = - * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId); - * - * } } } - */ - } - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } else { - error = result.right().value(); - } - if (isLeft) { - - // create new entry in ES - res = true; - if (artifactData.getData() != null) { - if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) - artifactData.setId(artifactDefinition.getEsId()); - res = saveArtifacts(artifactData, parentId, false); - - } - } - - if (res) { - log.debug("Artifact saved into ES - {}", artifactUniqueId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - // resultOp = Either.left(result.left().value()); - // return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - // return resultOp; - } - } - - return resultOp; - } - - private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) { - log.trace("Starting payload handling"); - byte[] payload = artifactInfo.getPayloadData(); - byte[] decodedPayload = null; - - if (payload != null && payload.length != 0) { - // the generated artifacts were already decoded by the handler - decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload); - if (decodedPayload.length == 0) { - log.debug("Failed to decode the payload."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - - String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload); - artifactInfo.setArtifactChecksum(checkSum); - log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum); - - // Specific payload validations of different types - Either<Boolean, ResponseFormat> isValidPayload = Either.left(true); - if (isDeploymentArtifact(artifactInfo)) { - log.trace("Starting deployment artifacts payload validation"); - String artifactType = artifactInfo.getArtifactType(); - if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { - isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType); - if (isValidPayload.isLeft()) { - isValidPayload = extractHeatParameters(artifactInfo); - } - } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) { - isValidPayload = validateXmlPayload(decodedPayload, artifactType); - // else - // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType) - // || ){ - } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) { - String artifactFileName = artifactInfo.getArtifactName(); - String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase(); - switch (fileExtension) { - case "xml": - isValidPayload = validateXmlPayload(decodedPayload, artifactType); - break; - case "json": - isValidPayload = validateJsonPayload(decodedPayload, artifactType); - break; - case "yml": - case "yaml": - isValidPayload = validateYmlPayload(decodedPayload, artifactType); - break; - } - } - } - if (isValidPayload.isRight()) { - ResponseFormat responseFormat = isValidPayload.right().value(); - return Either.right(responseFormat); - } - - } // null/empty payload is normal if called from metadata update ONLY. - // The validation of whether this is metadata/payload update case is - // currently done separately - else { - if (!isArtifactMetadataUpdate) { - log.debug("Payload is missing."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - return Either.right(responseFormat); - } - } - log.trace("Ended payload handling"); - return Either.left(decodedPayload); - } - - private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) { - // Basic YAML validation - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { - log.debug("Invalid YAML format"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); - return Either.right(responseFormat); - } - if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { - // HEAT specific YAML validation - DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class); - if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) { - log.debug("HEAT doesn't contain required \"heat_template_version\" section."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType); - return Either.right(responseFormat); - } - } - - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) { - Either<Boolean, ResponseFormat> res = Either.left(true); - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { - log.debug("Invalid YAML format"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); - res = Either.right(responseFormat); - } - - return res; - } - - private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) { - boolean isXmlValid = isValidXml(payload); - if (!isXmlValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType); - log.debug("Invalid XML content"); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) { - boolean isJsonValid = isValidJson(payload); - if (!isJsonValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type); - log.debug("Invalid JSON content"); - return Either.right(responseFormat); - } - return Either.left(true); - } - - public void handleTransaction(Either<Operation, ResponseFormat> opState) { - if (opState == null || opState.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - - public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock, - boolean inTransaction) { - User user = new User(); - user.setUserId(userUserId); - Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata); - if (parent.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value())); - return Either.right(responseFormat); - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName, - false, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); - } - Either<ArtifactDefinition, Operation> result = handleDelete.left().value(); - return Either.left(result.right().value()); - - } - - private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) { - Operation op = new Operation(); - long time = System.currentTimeMillis(); - op.setCreationDate(time); - - String artifactName = artifactInfo.getArtifactName(); - artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName)); - - op.setImplementation(artifactInfo); - op.setLastUpdateDate(time); - return op; - } - - private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) { - String newArtifactName = operationName + "_" + artifactName; - log.trace("converting artifact name {} to {}", artifactName, newArtifactName); - return newArtifactName; - } - - // download by MSO - public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { - - // General validation - if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - artifactName = ValidationUtils.normalizeFileName(artifactName); - - // Resource validation - Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); - if (validateResourceNameAndVersion.isRight()) { - return Either.right(validateResourceNameAndVersion.right().value()); - } - - Resource resource = validateResourceNameAndVersion.left().value(); - String resourceId = resource.getUniqueId(); - - // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Deployment artifacts of resource {} are not found", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - ArtifactDefinition deploymentArtifact = null; - - for (ArtifactDefinition artifactDefinition : artifacts.values()) { - if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) { - log.debug("Found deployment artifact {}", artifactName); - deploymentArtifact = artifactDefinition; - break; - } - } - - if (deploymentArtifact == null) { - log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null); - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", artifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - // download by MSO - public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { - - // General validation - if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - artifactName = ValidationUtils.normalizeFileName(artifactName); - - // Resource validation - /* - * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return - * Either.right(validateResourceNameAndVersion.right().value()); } - * - * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId(); - */ - - // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - Service service = validateServiceNameAndVersion.left().value(); - - // ResourceInstance validation - Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName); - if (validateResourceInstance.isRight()) { - return Either.right(validateResourceInstance.right().value()); - } - - ComponentInstance resourceInstance = validateResourceInstance.left().value(); - - Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); - - final String finalArtifactName = artifactName; - Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); - - boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName); - ArtifactDefinition deployableArtifact; - - if (!hasDeploymentArtifacts) { - log.debug("Deployment artifact with name {} not found", artifactName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - log.debug("Found deployment artifact {}", artifactName); - deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get(); - // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service ); - - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", artifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) { - - List<ComponentInstance> riList = service.getComponentInstances(); - for (ComponentInstance ri : riList) { - if (ri.getNormalizedName().equals(resourceInstanceName)) - return Either.left(ri); - } - - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName)); - } - - private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) { - - Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); - if (serviceListBySystemName.isRight()) { - log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName)); - } - List<Service> serviceList = serviceListBySystemName.left().value(); - if (serviceList == null || serviceList.isEmpty()) { - log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName)); - } - - Service foundService = null; - for (Service service : serviceList) { - if (service.getVersion().equals(serviceVersion)) { - log.trace("Found service with version {}", serviceVersion); - foundService = service; - break; - } - } - - if (foundService == null) { - log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion)); - } - return Either.left(foundService); - } - - private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) { - - Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); - if (resourceListBySystemName.isRight()) { - log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName)); - } - return Either.left(resourceListBySystemName.left().value()); - } - - public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { - // Validation - log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); - if (serviceName == null || serviceVersion == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); - - // Service validation - Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); - - // Looking for deployment or tosca artifacts - Service service = validateServiceNameAndVersion.left().value(); - - if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { - log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); - } - - Optional<ArtifactDefinition> foundArtifactOptl = null; - - if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { - foundArtifactOptl = service.getDeploymentArtifacts().values().stream() - // filters artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); - } - if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { - foundArtifactOptl = service.getToscaArtifacts().values().stream() - // filters TOSCA artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); - } - if (!foundArtifactOptl.isPresent()) { - log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); - } - log.debug("Found deployment artifact {}", normalizedArtifactName); - // Downloading the artifact - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service); - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", normalizedArtifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { - log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); - Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); - if (artifactById.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); - log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); - } - ArtifactDefinition artifactDefinition = artifactById.left().value(); - if (artifactDefinition == null) { - log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); - } - - return downloadArtifact(artifactDefinition, null); - } - - private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) { - boolean found = false; - Map<String, ArtifactDefinition> artifactsS = component.getArtifacts(); - if (artifactsS != null) { - for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts(); - if (!found && deploymentArtifactsS != null) { - for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts(); - if (!found && toscaArtifactsS != null) { - for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - switch (component.getComponentType()) { - case RESOURCE: - Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces(); - if (!found && interfaces != null) { - for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) { - Map<String, Operation> operations = entry.getValue().getOperationsMap(); - for (Map.Entry<String, Operation> entryOp : operations.entrySet()) { - if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - } - break; - case SERVICE: - Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts(); - if (!found && apiArtifacts != null) { - for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - break; - default: - - } - - return found; - } - - private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) { - - boolean found = false; - List<ComponentInstance> resourceInstances = component.getComponentInstances(); - ComponentInstance resourceInstance = null; - for (ComponentInstance ri : resourceInstances) { - if (ri.getUniqueId().equals(resourceInstanceId)) { - resourceInstance = ri; - break; - } - } - if (resourceInstance != null) { - Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); - if (artifacts != null) { - for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - if (!found) { - artifacts = resourceInstance.getArtifacts(); - if (artifacts != null) { - for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - } - } - return found; - } - - private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, - String containerComponentType, boolean inTransaction) { - - ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); - componentForAudit.getNodeType(); - - Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId); - - if (componentResult.isRight()) { - ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); - log.debug("Service not found, serviceId {}", componentId); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); - return Either.right(responseFormat); - } - return Either.left(componentResult.left().value()); - } - - private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation, - ComponentTypeEnum componentType) { - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) { - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - String uniqueId = component.getUniqueId(); - log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId); - handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null); - return Either.right(canWork.right().value()); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { - - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) { - String role = user.getRole(); - if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - return Either.left(true); - } - - private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction); - - if (validateUserExists.isRight()) { - User user = new User(); - user.setUserId(userId); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null); - return Either.right(validateUserExists.right().value()); - } - return Either.left(validateUserExists.left().value()); - } - - protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) { - AuditingActionEnum auditingAction = null; - switch (operation.getArtifactOperationEnum()) { - case Create: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD; - break; - case Update: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE; - break; - case Delete: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE; - break; - case Download: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD; - break; - default: - break; - } - return auditingAction; - } - - private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) { - String esArtifactId = artifactDefinition.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {}", actionStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()); - handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null); - - return Either.right(responseFormat); - } - - ESArtifactData esArtifactData = artifactfromES.left().value(); - byte[] data = esArtifactData.getDataAsArray(); - if (data == null) { - log.debug("Artifact data from ES is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName())); - } - String artifactName = artifactDefinition.getArtifactName(); - log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName); - return Either.left(new ImmutablePair<String, byte[]>(artifactName, data)); - } - - public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { - ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload); - return artifactData; - } - - private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) { - - CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); - - if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { - log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); - } else { - log.info("Failed to save artifact {}.", artifactData.getId()); - return false; - } - return true; - } - - private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) { - return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE)); - } - - private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) { - return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType())); - } - - public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { - Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction); - if (user.isRight()) { - ResponseFormat responseFormat; - if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(user.right().value()); - } - return Either.right(responseFormat); - } - - ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType); - return Either.left(artifactDefinition); - } - - public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); - String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE); - String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); - - artifactInfo.setArtifactDisplayName(artifactName); - artifactInfo.setArtifactLabel(logicalName.toLowerCase()); - artifactInfo.setArtifactType(artifactType); - artifactInfo.setDescription(artifactDescription); - artifactInfo.setArtifactGroupType(groupType); - nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo); - - setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo); - - return artifactInfo; - } - - private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) { - String uniqueId = null; - - if (resourceId != null) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); - artifactInfo.setUniqueId(uniqueId); - } - artifactInfo.setUserIdCreator(user.getUserId()); - String fullName = user.getFullName(); - artifactInfo.setUpdaterFullName(fullName); - - long time = System.currentTimeMillis(); - - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - artifactInfo.setMandatory(true); - } - - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) { - return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); - } - - public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { - return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); - } - - private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { - - byte[] payload = payloadStr.getBytes(); - - ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); - return Either.left(artifactData); - } - - /** - * - * @param artifactDefinition - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, String instanceId) { - String payload = generateHeatEnvPayload(artifactDefinition); - String prevUUID = artifactDefinition.getArtifactUUID(); - ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); - return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) - .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); - } - - public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, String instanceId) { - String payload = generateHeatEnvPayload(artifactDefinition); - String prevUUID = artifactDefinition.getArtifactUUID(); - ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); - return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) - .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); - } - - private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { - if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { + private static final String ARTIFACT_TYPE_OTHER = "OTHER"; + private static final String ARTIFACT_DESCRIPTION = "artifact description"; + private static final String ARTIFACT_LABEL = "artifact label"; + private static final String ARTIFACT_URL = "artifact url"; + private static final String ARTIFACT_NAME = "artifact name"; + private static final String ARTIFACT_PAYLOAD = "artifact payload"; + + private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; + private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; + private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; + + public static final String HEAT_ENV_NAME = "heatEnv"; + public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + public static final String HEAT_ENV_SUFFIX = "env"; + private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; + + private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @javax.annotation.Resource + private IInterfaceLifecycleOperation interfaceLifecycleOperation; + @javax.annotation.Resource + private IUserAdminOperation userOperaton; + + @javax.annotation.Resource + private IElementOperation elementOperation; + + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + @javax.annotation.Resource + private UserBusinessLogic userAdminManager; + + @javax.annotation.Resource + private IHeatParametersOperation heatParametersOperation; + + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + + @Autowired + private ToscaExportHandler toscaExportUtils; + + @Autowired + private CsarUtils csarUtils; + + @Autowired + private LifecycleBusinessLogic lifecycleBusinessLogic; + + @Autowired + private IUserBusinessLogic userBusinessLogic; + + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + + @Autowired + private ArtifactsResolver artifactsResolver; + + public enum ArtifactOperationEnum { + CREATE, UPDATE, DELETE, DOWNLOAD, LINK; + + public static boolean isCreateOrLink(ArtifactOperationEnum operation) { + return operation == CREATE || operation == LINK; + } + } + + public class ArtifactOperationInfo { + + private ArtifactOperationEnum artifactOperationEnum; + private boolean isExternalApi; + private boolean ignoreLifecycleState; + + public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { + this.artifactOperationEnum = artifactOperationEnum; + this.isExternalApi = isExternalApi; + this.ignoreLifecycleState = ignoreLifecycleState; + } + + public boolean isExternalApi() { + return isExternalApi; + } + + public boolean ignoreLifecycleState() { + return ignoreLifecycleState; + } + + public ArtifactOperationEnum getArtifactOperationEnum() { + return artifactOperationEnum; + } + + } + + // new flow US556184 + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { + return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { + + // step 1 - detect auditing type + AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); + // step 2 - check header + if (userId == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); + handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + // step 3 - check user existence + Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); + if (userResult.isRight()) { + return Either.right(userResult.right().value()); + } + + // step 4 - check user's role + User user = userResult.left().value(); + Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); + if (validateUserRole.isRight()) { + return Either.right(validateUserRole.right().value()); + } + + // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType); + if (validateComponent.isRight()) { + return Either.right(validateComponent.right().value()); + } + component = validateComponent.left().value(); + Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation); + if (validateWorkOnResource.isRight()) { + return Either.right(validateWorkOnResource.right().value()); + } + // step 8 + + return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, user, component, + shouldLock, inTransaction, true); + } + + /** + * This Method validates only the Artifact and does not validate user / role / component ect...<br> + * For regular usage use <br> + * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)} + * + * @return + */ + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, + ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + Component parent = component; + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + + AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); + artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction); + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; + if (errorWrapper.isEmpty()) { + // step 10 + result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, + Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition validatedArtifactInfo = artifactInfo; + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation + .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { + Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component); + if (validateArtifact.isRight()) { + ResponseFormat responseFormat = validateArtifact.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + errorWrapper.setInnerElement(validateArtifact.right().value()); + } + else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { + validatedArtifactInfo = validateArtifact.left().value(); + handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction); + } + } + return validatedArtifactInfo; + } + + private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, + ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition validatedArtifact = validateArtifact.left().value(); + + if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) + && ComponentTypeEnum.SERVICE == component.getComponentType()) { + ComponentInstance componentInstance = component.getComponentInstances() + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findAny() + .get(); + Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + + ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values() + .stream() + .filter(p -> p.getUniqueId() + .equals(validatedArtifact.getUniqueId())) + .findAny() + .get(); + Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance + .getName(), user, componentId, shouldLock, inTransaction); + if (eitherGenerated.isRight()) { + errorWrapper.setInnerElement(eitherGenerated.right().value()); + } + } + } + + private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { + boolean needGenerate; + needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component + .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType() + .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV + .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); + return needGenerate; + } + + private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) { + return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo + .getArtifactType() + .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, + boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); + if (generated.isRight()) { + return generated; + } + byte[] decodedPayload = artifactDefinition.getPayloadData(); + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload)); + return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition + .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null, + shouldLock, inTransaction); + + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { + log.debug("tosca artifact generation"); + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { + Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); + + if (generated.isRight()) { + log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right() + .value()); + + return Either.right(generated.right().value()); + } + byte[] value = generated.left().value(); + artifactInfo.setPayload(value); + + } + else { + Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent); + if (exportComponent.isRight()) { + log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right() + .value()); + ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status); + return Either.right(responseFormat); + } + log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); + String payload = exportComponent.left().value().getMainYaml(); + artifactInfo.setPayloadData(payload); + } + return Either.left(Either.left(artifactInfo)); + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, + String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + if (interfaceName != null && operationName != null) { + interfaceName = interfaceName.toLowerCase(); + operationName = operationName.toLowerCase(); + } + switch (operation.getArtifactOperationEnum()) { + case DOWNLOAD: + if (artifactGenerationRequired(parent, artifactInfo)) { + return generateNotSavedArtifact(parent, artifactInfo); + } + return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent); + case DELETE: + return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); + case UPDATE: + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) + && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { + result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); + if (needUpdateGroup && result.isLeft()) { + Either<ArtifactDefinition, Operation> updateResult = result.left().value(); + ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left() + .value(), parent, componentType, componentId); + if (error != ActionStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(error)); + } + } + } + else { + if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { + result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup); + } + } + if (result == null) { + result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + if (needUpdateGroup && result.isLeft()) { + Either<ArtifactDefinition, Operation> updateResult = result.left().value(); + + ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left() + .value(), parent, componentType); + if (error != ActionStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(error)); + } + } + } + return result; + case CREATE: + return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + case LINK: + return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction); + } + return null; + } + + private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) { + List<GroupDefinition> groups = parent.getGroups(); + if (groups != null && !groups.isEmpty()) { + List<GroupDataDefinition> groupToUpdate = groups.stream() + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfo + .getUniqueId())) + .collect(Collectors.toList()); + if (groupToUpdate != null && !groupToUpdate.isEmpty()) { + groupToUpdate.forEach(g -> { + g.getArtifacts().remove(artifactInfo.getUniqueId()); + g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID()); + g.getArtifacts().add(artAfterUpdate.getUniqueId()); + g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); + }); + Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); + } + } + } + return ActionStatus.OK; + } + + private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) { + List<GroupDefinition> groups = parent.getGroups(); + if (groups != null && !groups.isEmpty()) { + List<GroupDataDefinition> groupToUpdate = groups.stream() + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfoHeat + .getUniqueId())) + .collect(Collectors.toList()); + if (groupToUpdate != null && !groupToUpdate.isEmpty()) { + groupToUpdate.forEach(g -> { + g.getArtifacts().remove(artifactInfoHeat.getUniqueId()); + g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID()); + g.getArtifacts().remove(artifactInfoHeatE.getUniqueId()); + g.getArtifacts().add(artHeatAfterUpdate.getUniqueId()); + g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID()); + g.getArtifacts().add(artHEAfterUpdate.getUniqueId()); + }); + Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); + } + } + } + return ActionStatus.OK; + } + + private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) { + List<GroupInstance> updatedGroupInstances = new ArrayList<>(); + List<GroupInstance> groupInstances = null; + Optional<ComponentInstance> componentInstOp = parent.getComponentInstances() + .stream() + .filter(ci -> ci.getUniqueId().equals(parentId)) + .findFirst(); + if (componentInstOp.isPresent()) { + groupInstances = componentInstOp.get().getGroupInstances(); + } + if (CollectionUtils.isNotEmpty(groupInstances)) { + boolean isUpdated = false; + for (GroupInstance groupInstance : groupInstances) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() + .contains(artifactInfo + .getUniqueId())) { + groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId()); + groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId()); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid() + .contains(artifactInfo + .getArtifactUUID())) { + groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); + groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroupInstances.add(groupInstance); + } + } + } + Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); + } + return ActionStatus.OK; + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result; + if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { + result = generateToscaArtifact(parent, artifactInfo, false, false); + } + else { + String heatArtifactId = artifactInfo.getGeneratedFromId(); + Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); + if (heatRes.isRight()) { + log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo + .getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes + .right() + .value()), ""); + return Either.right(responseFormat); + } + String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); + artifactInfo.setPayloadData(generatedPayload); + result = Either.left(Either.left(artifactInfo)); + } + return result; + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) { + convertParentType(componentType); + String parentId = parent.getUniqueId(); + Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo + .getGeneratedFromId()); + ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); + + if (origMd5 != null) { + Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { + + Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + else { // duplicate + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + + // lock resource + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + try { + resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup); + return resultOp; + + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + if (!inTransaction) { + titanDao.rollback(); + } + } + else { + log.debug("all changes committed"); + if (!inTransaction) { + titanDao.commit(); + } + } + if (shouldLock) { + graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType()); + } + } + } + + public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { + if (artifactGenerationRequired(component, csarArtifact)) { + Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false); + + if (generated.isRight()) { + log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right() + .value()); + + return Either.right(generated.right().value()); + } + return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left() + .value())); + } + return downloadArtifact(csarArtifact); + } + + public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { + // perform all validation in common flow + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, + null, parentId, containerComponentType); + if (result.isRight()) { + return Either.right(result.right().value()); + } + ArtifactDefinition artifactDefinition; + Either<ArtifactDefinition, Operation> insideValue = result.left().value(); + if (insideValue.isLeft()) { + artifactDefinition = insideValue.left().value(); + } + else { + artifactDefinition = insideValue.right().value().getImplementationArtifact(); + } + // for tosca artifacts and heat env on VF level generated on download without saving + if (artifactDefinition.getPayloadData() != null) { + return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition + .getPayloadData())); + } + return downloadArtifact(artifactDefinition); + } + + public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { + // step 1 + // detect auditing type + Map<String, ArtifactDefinition> resMap = null; + Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null; + + new Wrapper<>(); + // step 2 + // check header + if (userId == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + } + // step 3 + // check user existence + // step 4 + // check user's role + + Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false); + if (userResult.isRight()) { + + resultOp = Either.right(userResult.right().value()); + return resultOp; + } + + userResult.left().value(); + + // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; + ComponentParametersView componentFilter = new ComponentParametersView(); + componentFilter.disableAll(); + componentFilter.setIgnoreArtifacts(false); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + componentFilter.setIgnoreComponentInstances(false); + } + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum + .findByParamName(containerComponentType), componentFilter); + + if (validateComponent.isRight()) { + resultOp = Either.right(validateComponent.right().value()); + return resultOp; + } + component = validateComponent.left().value(); + Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock "); + if (lockComponent.isRight()) { + + resultOp = Either.right(lockComponent.right().value()); + return resultOp; + } + + try { + ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); + + if (groupType == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + + } + if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); + if (list != null && !list.isEmpty()) { + resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); + } + else { + resMap = new HashMap<>(); + } + resultOp = Either.left(resMap); + return resultOp; + } + else { + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType + .getNodeType(), groupType, componentId); + if (artifactsMapStatus.isRight()) { + if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + resultOp = Either.right(responseFormat); + } + else { + resMap = new HashMap<>(); + resultOp = Either.left(resMap); + } + } + else { + resMap = artifactsMapStatus.left().value(); + resultOp = Either.left(resMap); + } + return resultOp; + } + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + titanDao.rollback(); + } + else { + log.debug("all changes committed"); + titanDao.commit(); + } + + componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } + + } + + private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) { + // step 9 + // check artifact existence + Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component + .getUniqueId()); + if (artifactResult.isRight()) { + if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); + log.debug("addArtifact - artifact {} not found", artifactId); + return Either.right(responseFormat); + + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult + .right() + .value())); + log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right() + .value()); + return Either.right(responseFormat); + } + } + // step 9.1 + // check artifact belong to component + boolean found = false; + switch (componentType) { + case RESOURCE: + case SERVICE: + found = checkArtifactInComponent(component, artifactId); + break; + case RESOURCE_INSTANCE: + found = checkArtifactInResourceInstance(component, componentId, artifactId); + break; + default: + + } + if (!found) { + String componentName = componentType.name().toLowerCase(); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName); + log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId); + return Either.right(responseFormat); + } + return Either.left(artifactResult.left().value()); + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + String artifactId = null; + + // step 11 + Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); + if (payloadEither.isRight()) { + return Either.right(payloadEither.right().value()); + } + byte[] decodedPayload = payloadEither.left().value(); + convertParentType(componentType); + + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + + try { + resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName); + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + + } + + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + Component parent, boolean shouldLock, boolean inTransaction) { + + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + + try { + resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + + } + + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + convertParentType(componentType); + + // lock resource + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); + + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + try { + resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName); + return resultOp; + + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + } + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); + + if (payloadEither.isRight()) { + return Either.right(payloadEither.right().value()); + } + byte[] decodedPayload = payloadEither.left().value(); + + return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); + } + + private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + Component parent, String origMd5, String originData, String interfaceType, String operationName) { + // Md5 validations + Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + // step 11 + Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent); + if (validateResult.isRight()) { + ResponseFormat responseFormat = validateResult.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(validateResult.right().value()); + } + + Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + log.debug("Error during handle payload"); + return Either.right(responseFormat); + } + + // validate heat parameters. this part must be after the parameters are + // extracted in "handlePayload" + Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo + .getArtifactType()); + if (validateAndConvertHeatParamers.isRight()) { + ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); + handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); + log.debug("Error during handle payload"); + return Either.right(responseFormat); + } + return payloadEither; + } + + public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, + ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { + + if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType() + .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { + return; + } + String artifactData = buildAuditingArtifactData(artifactDefinition); + + if (user == null) { + user = new User(); + user.setUserId("UNKNOWN"); + } + switch (componentTypeEnum) { + case RESOURCE: + Resource resource = (Resource) component; + if (resource == null) { + // In that case, component ID should be instead of name + resource = new Resource(); + resource.setName(componentId); + } + componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum, + ResourceAuditData.newBuilder() + .artifactUuid(prevArtifactUuid) + .build(), currentArtifactUuid, artifactData); + break; + + case SERVICE: + Service service = (Service) component; + if (service == null) { + // In that case, component ID should be instead of name + service = new Service(); + service.setName(componentId); + } + componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(), + null, null, artifactData, null); + break; + + case RESOURCE_INSTANCE: + if (resourceInstanceName == null) { + resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId); + } + componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, + ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(), + resourceInstanceName, null, artifactData, null); + break; + default: + break; + } + } + + private String getResourceInstanceNameFromComponent(Component component, String componentId) { + ComponentInstance resourceInstance = component.getComponentInstances() + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findFirst() + .orElse(null); + String resourceInstanceName = null; + if (resourceInstance != null) { + resourceInstanceName = resourceInstance.getName(); + } + return resourceInstanceName; + } + + public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) { + Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + // Putting together artifact info + String artifactData = buildAuditingArtifactData(artifactDefinition); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid); + return auditingFields; + } + + // ----- + + private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) { + StringBuilder sb = new StringBuilder(); + if (artifactDefinition != null) { + sb.append(artifactDefinition.getArtifactGroupType().getType()) + .append(",") + .append("'") + .append(artifactDefinition.getArtifactLabel()) + .append("'") + .append(",") + .append(artifactDefinition.getArtifactType()) + .append(",") + .append(artifactDefinition.getArtifactName()) + .append(",") + .append(artifactDefinition.getTimeout()) + .append(",") + .append(artifactDefinition.getEsId()); + + sb.append(","); + if (artifactDefinition.getArtifactVersion() != null) { + + sb.append(artifactDefinition.getArtifactVersion()); + } + else { + sb.append(" "); + } + sb.append(","); + if (artifactDefinition.getArtifactUUID() != null) { + sb.append(artifactDefinition.getArtifactUUID()); + } + else { + sb.append(" "); + } + } + return sb.toString(); + } + + private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { + + if (origMd5 != null) { + String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData); + if (!encodeBase64Str.equals(origMd5)) { + log.debug("The calculated md5 is different then the received one"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + } + } + else { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) { + log.debug("Missing md5 header during artifact create"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + } + // Update metadata + if (payload != null && payload.length != 0) { + log.debug("Cannot have payload while md5 header is missing"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + return Either.left(true); + } + + private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, + ComponentTypeEnum componentType, Component parentComponent) { + + Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); + if (artifactById.isRight()) { + return Either.right(artifactById.right().value()); + } + ArtifactDefinition currentArtifactInfo = artifactById.left().value(); + + ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo); + Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); + if (validateInformationalArtifactRes.isRight()) { + return Either.right(validateInformationalArtifactRes.right().value()); + } + Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); + if (validateAndSetArtifactname.isRight()) { + return Either.right(validateAndSetArtifactname.right().value()); + } + if (operationName != null && interfaceName != null) { + operationName = operationName.toLowerCase(); + interfaceName = interfaceName.toLowerCase(); + } + Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType); + if (logicalNameStatus.isRight()) { + return Either.right(logicalNameStatus.right().value()); + } + // This is a patch to block possibility of updating service api fields + // through other artifacts flow + + ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL; + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType); + } + else { + checkCreateFields(user, artifactInfo, artifactGroupType); + } + + composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName); + if (currentArtifactInfo != null) { + artifactInfo.setMandatory(currentArtifactInfo.getMandatory()); + } + + // artifactGroupType is not allowed to be updated + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); + if (validateGroupType.isRight()) { + return Either.right(validateGroupType.right().value()); + } + } + // TODO TEMP !!! + NodeTypeEnum parentType = convertParentType(componentType); + + // TODO TEMP !!! + boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); + + if (isDeploymentArtifact(artifactInfo)) { + Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType); + if (deploymentValidationResult.isRight()) { + return Either.right(deploymentValidationResult.right().value()); + } + } + else { + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + } + + Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo); + if (descriptionResult.isRight()) { + return Either.right(descriptionResult.right().value()); + } + + if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType() + .equals(ArtifactGroupTypeEnum.SERVICE_API)) { + Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType); + if (validateServiceApiType.isRight()) { + return Either.right(validateServiceApiType.right().value()); + } + // Change of type is not allowed and should be ignored + + artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER); + + Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo); + if (validateUrl.isRight()) { + return Either.right(validateUrl.right().value()); + } + + Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo); + if (validateUpdate.isRight()) { + log.debug("serviceApi first update cnnot be without payload."); + return Either.right(validateUpdate.right().value()); + } + } + else { + Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType); + if (validateArtifactType.isRight()) { + return Either.right(validateArtifactType.right().value()); + } + if (artifactInfo.getApiUrl() != null) { + artifactInfo.setApiUrl(null); + log.error("Artifact URL cannot be set through this API - ignoring"); + } + + if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) { + artifactInfo.setServiceApi(false); + log.error("Artifact service API flag cannot be changed - ignoring"); + } + } + + return Either.left(artifactInfo); + } + + private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) { + if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) { + artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); + artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType()); + artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel()); + } + } + + private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { + + Either<ArtifactDefinition, ResponseFormat> result = null; + ArtifactDefinition foundArtifact = null; + if (StringUtils.isNotEmpty(artifactId)) { + foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); + } + if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + log.debug("Artifact {} already exist", artifactId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); + } + if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + } + if (result == null) { + result = Either.left(foundArtifact); + } + return result; + } + + private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { + ArtifactDefinition foundArtifact; + if (parentComponent.getUniqueId().equals(parentId)) { + foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); + } + else { + ComponentInstance instance = findComponentInstance(parentId, parentComponent); + foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); + } + return foundArtifact; + } + + private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { + ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + Either<Boolean, ResponseFormat> validationResult = Either.left(true); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { + String artifactTypeName = artifactType.getType(); + ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); + Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInformationalArtifacts(); + Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet(); + if (!validArtifactTypes.contains(artifactTypeName)) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } + else { + List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName) + .getValidForResourceTypes(); + if (!validResourceType.contains(parentResourceType.name())) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } + } + } + return validationResult; + } + + private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { + if (componentType.equals(ComponentTypeEnum.RESOURCE)) { + return NodeTypeEnum.Resource; + } + else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + return NodeTypeEnum.ResourceInstance; + } + else { + return NodeTypeEnum.Service; + } + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, + boolean shouldLock, boolean inTransaction) { + + NodeTypeEnum parentType = convertParentType(componentType); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null; + ArtifactDefinition foundArtifact = null; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null; + org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; + boolean isDuplicated = false; + String esId = null; + Either<Boolean, StorageOperationStatus> needCloneRes = null; + try { + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + resultOp = Either.right(lockComponent.right().value()); + } + } + if (resultOp == null) { + log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); + getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes + .right() + .value()), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null) { + fetchedContainerComponent = getContainerRes.left().value(); + log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); + getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); + if (getArtifactRes.isRight()) { + log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent + .getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right() + .value(), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + else { + foundArtifact = getArtifactRes.left().value().getLeft(); + esId = foundArtifact.getEsId(); + } + } + if (resultOp == null && StringUtils.isNotEmpty(esId)) { + needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent + .getComponentType())); + if (needCloneRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + boolean isNeedToDeleteArtifactFromDB = true; + if (resultOp == null) { + + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + String instanceId = parentId; + Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); + + if (isOnlyResourceInstanceArtifact.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right() + .value(), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); + } + + Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes + .left() + .value()); + if (updatedArtifactRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + else { + isDuplicated = updatedArtifactRes.left().value().getDuplicated(); + } + } + + if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) { + log.debug("Going to delete the artifact {} from the database. ", artifactId); + CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); + if (cassandraStatus != CassandraOperationStatus.OK) { + log.debug("Failed to delete the artifact {} from the database. ", artifactId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + + List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes + .left() + .value() + .getRight() + .getGroupInstances()); + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { + List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent + .getGroups()); + if (CollectionUtils.isNotEmpty(updatedGroups)) { + Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + } + if (resultOp == null) { + resultOp = Either.left(Either.left(foundArtifact)); + handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); + } + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + } + } + + private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) { + Either<Boolean, ActionStatus> result = Either.left(true); + ComponentInstance foundInstance = null; + Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId().equals(instanceId)) + .findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } + else { + foundInstance = componentInstanceOpt.get(); + String componentUid = foundInstance.getComponentUid(); + Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", componentUid); + return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); + } + Component origComponent = getContainerRes.left().value(); + Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts(); + if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) { + Optional<String> op = deploymentArtifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return Either.left(false); + } + } + Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts(); + if (artifacts != null && !artifacts.isEmpty()) { + Optional<String> op = artifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return Either.left(false); + } + } + + } + return result; + } + + private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) { + List<GroupDataDefinition> updatedGroups = new ArrayList<>(); + boolean isUpdated = false; + if (groups != null) { + for (GroupDefinition group : groups) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) { + group.getArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid() + .contains(foundArtifact.getArtifactUUID())) { + group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroups.add(group); + } + } + } + return updatedGroups; + } + + private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) { + List<GroupInstance> updatedGroupInstances = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(groupInstances)) { + boolean isUpdated = false; + for (GroupInstance groupInstance : groupInstances) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() + .contains(artifactId)) { + groupInstance.getGroupInstanceArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid() + .contains(foundArtifact + .getArtifactUUID())) { + groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroupInstances.add(groupInstance); + } + } + } + return updatedGroupInstances; + } + + private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { + + Either<ArtifactDataDefinition, StorageOperationStatus> result; + boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); + String componentId = component.getUniqueId(); + String instanceId = componentId.equals(parentId) ? null : parentId; + if (isMandatory) { + log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); + resetMandatoryArtifactFields(foundArtifact); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); + } + else if (cloneIsNeeded) { + log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); + } + else { + log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); + } + return result; + } + + private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { + + Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null; + Map<String, ArtifactDefinition> artifacts = new HashMap<>(); + ComponentInstance foundInstance = null; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { + Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId() + .equals(parentId)) + .findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } + else { + foundInstance = componentInstanceOpt.get(); + fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); + } + } + else { + fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); + } + if (result == null) { + if (artifacts.containsKey(artifactId)) { + result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); + } + else { + result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); + } + } + return result; + } + + private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) { + Map<String, ArtifactDefinition> currArtifacts; + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { + currArtifacts = component.getDeploymentArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getToscaArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) { + Map<String, ArtifactDefinition> currArtifacts; + if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { + currArtifacts = instance.getDeploymentArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { + currArtifacts = instance.getArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { + StorageOperationStatus result; + switch (cassandraStatus) { + case OK: + result = StorageOperationStatus.OK; + break; + case NOT_FOUND: + result = StorageOperationStatus.NOT_FOUND; + break; + case CLUSTER_NOT_CONNECTED: + case KEYSPACE_NOT_CONNECTED: + result = StorageOperationStatus.CONNECTION_FAILURE; + break; + default: + result = StorageOperationStatus.GENERAL_ERROR; + break; + } + return result; + } + + private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { + if (fetchedArtifact != null) { + log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); + fetchedArtifact.setEsId(null); + fetchedArtifact.setArtifactName(null); + fetchedArtifact.setDescription(null); + fetchedArtifact.setApiUrl(null); + fetchedArtifact.setArtifactChecksum(null); + nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact); + fetchedArtifact.setArtifactUUID(null); + long time = System.currentTimeMillis(); + fetchedArtifact.setPayloadUpdateDate(time); + fetchedArtifact.setHeatParameters(null); + fetchedArtifact.setHeatParamsUpdateDate(null); + } + } + + private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) { + StorageOperationStatus error = StorageOperationStatus.OK; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + log.debug("Need to re-generate customization UUID for instance {}", instanceId); + error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + return error; + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, + Component parent) { + Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent + .getUniqueId()); + if (artifactById.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); + log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, ""); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + ArtifactDefinition artifactDefinition = artifactById.left().value(); + if (artifactDefinition == null) { + log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); + return Either.left(insideEither); + } + + private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName, + ComponentTypeEnum componentType) { + + String artifactLabel = artifactInfo.getArtifactLabel(); + if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel() + .isEmpty())) { + BeEcompErrorManager.getInstance() + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + log.debug("missing artifact logical name for component {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); + } + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) { + + if (operationName != null) { + if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { + log.debug("artifact label cannot be set {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); + } + else { + artifactLabel = operationName; + } + } + String displayName = artifactInfo.getArtifactDisplayName(); + if (displayName == null || displayName.isEmpty()) { + displayName = artifactLabel; + } + displayName = ValidationUtils.cleanArtifactDisplayName(displayName); + artifactInfo.setArtifactDisplayName(displayName); + + if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { + log.debug("Invalid format form Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel); + + if (artifactLabel.isEmpty()) { + log.debug("missing normalized artifact logical name for component {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); + } + + if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) { + log.debug("Invalid lenght form Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String + .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); + } + if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) { + log.debug("Non unique Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); + } + } + artifactInfo.setArtifactLabel(artifactLabel); + + return Either.left(ActionStatus.OK); + } + + private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) { + boolean isUnique = true; + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts; + if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); + } + else { + artifacts = artifactToscaOperation.getArtifacts(componentId); + } + + if (artifacts.isLeft()) { + for (String label : artifacts.left().value().keySet()) { + if (label.equals(artifactLabel)) { + isUnique = false; + break; + } + } + } + if (componentType.equals(ComponentTypeEnum.RESOURCE)) { + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation + .getAllInterfacesOfResource(componentId, true, true); + if (allInterfacesOfResource.isLeft()) { + for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { + for (Operation operation : interace.getOperationsMap().values()) { + if (operation.getImplementation() != null && operation.getImplementation() + .getArtifactLabel() + .equals(artifactLabel)) { + isUnique = false; + break; + } + } + } + } + } + return isUnique; + } + + // *************************************************************** + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + Either<ArtifactDefinition, Operation> insideEither = null; + ComponentInstance foundInstance = findComponentInstance(parentId, parent); + String instanceId = null; + String instanceName = null; + if (foundInstance != null) { + instanceId = foundInstance.getUniqueId(); + instanceName = foundInstance.getName(); + } + boolean isLeft = false; + String artifactUniqueId = null; + StorageOperationStatus error = null; + // information/deployment/api aritfacts + log.trace("Try to create entry on graph"); + NodeTypeEnum nodeType = convertParentType(componentTypeEnum); + Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent + .getUniqueId(), nodeType, true, instanceId); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + result.left().value(); + + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + if (isLeft) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + return resultOp; + } + else { + log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo + .getArtifactDisplayName()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); + resultOp = Either.right(responseFormat); + return resultOp; + + } + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { + + ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + Either<ArtifactDefinition, Operation> insideEither = null; + ComponentInstance foundInstance = findComponentInstance(parentId, parent); + String instanceId = null; + String instanceName = null; + if (foundInstance != null) { + if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) { + log.debug("Failed to create artifact, already exists"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo + .getArtifactLabel()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance + .getName()); + resultOp = Either.right(responseFormat); + return resultOp; + } + + instanceId = foundInstance.getUniqueId(); + instanceName = foundInstance.getName(); + } + if (artifactData == null) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); + log.debug("Failed to create artifact object for ES."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); + resultOp = Either.right(responseFormat); + return resultOp; + + } + // set on graph object id of artifact in ES! + artifactInfo.setEsId(artifactData.getId()); + + boolean isLeft = false; + String artifactUniqueId = null; + StorageOperationStatus error = null; + if (interfaceType != null && operationName != null) { + // lifecycle artifact + Operation operation = convertToOperation(artifactInfo, operationName); + + Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getImplementation().getUniqueId(); + result.left().value().getImplementation(); + + insideEither = Either.right(result.left().value()); + resultOp = Either.left(insideEither); + } + else { + error = result.right().value(); + } + } + else { + // information/deployment/api aritfacts + log.trace("Try to create entry on graph"); + NodeTypeEnum nodeType = convertParentType(componentTypeEnum); + Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent + .getUniqueId(), nodeType, true, instanceId); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + artifactData.setId(result.left().value().getEsId()); + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + else { + error = result.right().value(); + } + } + if (isLeft) { + boolean res = saveArtifacts(artifactData, parentId); + + if (res) { + log.debug("Artifact saved into ES - {}", artifactUniqueId); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + return resultOp; + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + + resultOp = Either.right(responseFormat); + return resultOp; + } + } + else { + log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo + .getArtifactDisplayName()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); + resultOp = Either.right(responseFormat); + return resultOp; + } + + } + + private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + foundInstance = containerComponent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId().equals(componentInstanceId)) + .findFirst() + .orElse(null); + } + return foundInstance; + } + + private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { + + Either<Boolean, ResponseFormat> result = Either.left(true); + Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>(); + + validateArtifactTypeExists(responseWrapper, artifactInfo); + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + + Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); + + if (responseWrapper.isEmpty()) { + validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); + } + + // Common code for all types + // not allowed to change artifactType + if (responseWrapper.isEmpty() && !isCreate) { + Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact); + if (validateServiceApiType.isRight()) { + responseWrapper.setInnerElement(validateServiceApiType.right().value()); + } + } + if (responseWrapper.isEmpty()) { + if (parentType.equals(NodeTypeEnum.Resource)) { + Resource resource = (Resource) parentComponent; + ResourceTypeEnum resourceType = resource.getResourceType(); + ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); + if (config == null) { + responseWrapper.setInnerElement(ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + else { + List<String> myList = config.getValidForResourceTypes(); + Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList); + if (either.isRight()) { + responseWrapper.setInnerElement(either.right().value()); + } + } + } + + validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); + } + + if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) { + String artifactName = artifactInfo.getArtifactName(); + if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) { + validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType); + } + } + + if (responseWrapper.isEmpty()) { + switch (artifactType) { + case HEAT: + case HEAT_VOL: + case HEAT_NET: + result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact); + break; + case HEAT_ENV: + result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; + case DCAE_INVENTORY_TOSCA: + case DCAE_INVENTORY_JSON: + case DCAE_INVENTORY_POLICY: + // Validation is done in handle payload. + case DCAE_INVENTORY_DOC: + case DCAE_INVENTORY_BLUEPRINT: + case DCAE_INVENTORY_EVENT: + // No specific validation + default: + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; + } + + } + + if (!responseWrapper.isEmpty()) { + result = Either.right(responseWrapper.getInnerElement()); + } + return result; + } + + private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) { + if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + } + } + + private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { + Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null; + if (parentType.equals(NodeTypeEnum.Resource)) { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts(); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); + } + else { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts(); + } + return resourceDeploymentArtifacts; + } + + public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) { + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + } + } + + private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + ArtifactTypeConfig retConfig = null; + String fileType = artifactType.getType(); + if (parentType.equals(NodeTypeEnum.Resource)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts() + .get(fileType); + } + else if (parentType.equals(NodeTypeEnum.Service)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts() + .get(fileType); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts() + .get(fileType); + } + return retConfig; + } + + private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) { + // extract heat parameters + if (artifactInfo.getPayloadData() != null) { + String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); + Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo + .getArtifactType()); + if (heatParameters.isRight() && (!heatParameters.right() + .value() + .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { + log.info("failed to parse heat parameters "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo + .getArtifactType()); + return Either.right(responseFormat); + } + else if (heatParameters.isLeft() && heatParameters.left().value() != null) { + artifactInfo.setListHeatParameters(heatParameters.left().value()); + } + } + return Either.left(true); + + } + + // Valid extension + public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + String fileType = artifactType.getType(); + List<String> acceptedTypes = null; + ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); + if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { + log.debug("parent type of artifact can be either resource or service"); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return; + } + + if (deploymentAcceptedTypes == null) { + log.debug("parent type of artifact can be either resource or service"); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + return; + } + else { + acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); + } + /* + * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. + */ + + String artifactName = artifactInfo.getArtifactName(); + String fileExtension = GeneralUtility.getFilenameExtension(artifactName); + // Pavel - File extension validation is case-insensitive - Ella, + // 21/02/2016 + if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) { + log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType)); + return; + } + } + + private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { + + Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>(); + Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>(); + Wrapper<byte[]> payloadWrapper = new Wrapper<>(); + + if (errorWrapper.isEmpty()) { + validateValidYaml(errorWrapper, artifactInfo); + } + + if (errorWrapper.isEmpty()) { + // Validate Heat Exist + validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent + .getComponentType()); + } + + if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { + fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); + } + + if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { + validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); + } + + // init Response + Either<Boolean, ResponseFormat> eitherResponse; + if (errorWrapper.isEmpty()) { + eitherResponse = Either.left(true); + } + else { + eitherResponse = Either.right(errorWrapper.getInnerElement()); + } + return eitherResponse; + } + + public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) { + if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) { + Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition); + if (fillArtifactPayload.isRight()) { + errorWrapper.setInnerElement(fillArtifactPayload.right().value()); + log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); + } + } + else { + payloadWrapper.setInnerElement(artifactDefinition.getPayloadData()); + } + } + + public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) { + Either<Boolean, ResponseFormat> result = Either.left(true); + Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD + .getEsId()); + if (eitherArtifactData.isLeft()) { + byte[] data = eitherArtifactData.left().value().getDataAsArray(); + data = Base64.encodeBase64(data); + payloadWrapper.setInnerElement(data); + } + else { + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData + .right() + .value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); + result = Either.right(responseFormat); + } + return result; + + } + + @SuppressWarnings("unchecked") + private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { + String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); + Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload); + String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); + Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload); + + Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS); + Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS); + if (eitherHeatEnvProperties.isRight()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); + errorWrapper.setInnerElement(responseFormat); + log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); + } + else if (eitherHeatProperties.isRight()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact + .getArtifactName(), heatArtifact.getArtifactName()); + errorWrapper.setInnerElement(responseFormat); + log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact + .getArtifactName()); + } + else { + Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); + Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); + heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); + if (!heatEnvPropertiesKeys.isEmpty()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact + .getArtifactName(), heatArtifact.getArtifactName()); + errorWrapper.setInnerElement(responseFormat); + } + } + } + + private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) { + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); + if (!isYamlValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo + .getArtifactType()); + errorWrapper.setInnerElement(responseFormat); + log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName()); + } + } + + private boolean isValidXml(byte[] xmlToParse) { + boolean isXmlValid = true; + try { + XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + setFeatures(reader); + reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse))); + } + catch (ParserConfigurationException | IOException | SAXException e) { + log.debug("Xml is invalid : {}", e.getMessage(), e); + isXmlValid = false; + } + return isXmlValid; + } + + private void setFeatures(XMLReader reader) throws SAXNotSupportedException { + try { + reader.setFeature("http://apache.org/xml/features/validation/schema", false); + reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + } + catch (SAXNotRecognizedException e) { + log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); + } + } + + private boolean isValidJson(byte[] jsonToParse) { + String parsed = new String(jsonToParse); + try { + gson.fromJson(parsed, Object.class); + } + catch (Exception e) { + log.debug("Json is invalid : {}", e.getMessage(), e); + return false; + } + return true; + } + + private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) { + boolean artifactNameFound = false; + Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null) + .iterator(); + + while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) { + artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()); + } + if (artifactNameFound) { + String parentName = parentComponent.getName(); + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType + .name(), parentName, artifactName); + + errorWrapper.setInnerElement(responseFormat); + log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); + + } + } + + private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, + ComponentTypeEnum componentType) { + Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); + if (res.isRight()) { + ResponseFormat responseFormat; + if (res.right().value() == StorageOperationStatus.NOT_FOUND) { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } + else { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } + errorWrapper.setInnerElement(responseFormat); + return; + } + ArtifactDefinition heatArtifact = res.left().value(); + heatArtifactMDWrapper.setInnerElement(heatArtifact); + } + + private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); + // timeout > 0 for HEAT artifacts + Integer timeout = artifactInfo.getTimeout(); + if (timeout == null) { + Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout(); + artifactInfo.setTimeout(defaultTimeout); + // HEAT artifact but timeout is invalid + } + else if (timeout < 1) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT)); + } + + // US649856 - Allow several HEAT files on Resource + log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel()); + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) { + String listToString = (typeList != null) ? typeList.toString() : ""; + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo + .getArtifactName(), listToString, resourceType.getValue()); + Either<Boolean, ResponseFormat> either = Either.right(responseFormat); + String resourceTypeName = resourceType.name(); + if (typeList != null && typeList.contains(resourceTypeName)) { + either = Either.left(true); + } + return either; + } + + private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { + if (artifactInfo.getHeatParameters() != null) { + for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { + String parameterType = heatParam.getType(); + HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType); + String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType(); + if (heatParameterType == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam + .getType()); + return Either.right(responseFormat); + } + + StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty); + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam + .getType(), heatParam.getName()); + return Either.right(responseFormat); + } + } + } + return Either.left(artifactInfo); + } + + public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) { + List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>(); + if (parentComponent.getDeploymentArtifacts() != null) { + if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) { + Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null); + if (getRI.isRight()) { + return deploymentArtifacts; + } + ComponentInstance ri = getRI.left().value(); + if (ri.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); + } + } + else if (parentComponent.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); + } + } + return deploymentArtifacts; + } + + private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) { + // on create if null add informational to current + if (artifactInfo.getArtifactGroupType() == null) { + artifactInfo.setArtifactGroupType(type); + } + if (artifactInfo.getUniqueId() != null) { + log.error("artifact uniqid cannot be set ignoring"); + } + artifactInfo.setUniqueId(null); + + if (artifactInfo.getArtifactRef() != null) { + log.error("artifact ref cannot be set ignoring"); + } + artifactInfo.setArtifactRef(null); + + if (artifactInfo.getArtifactRepository() != null) { + log.error("artifact repository cannot be set ignoring"); + } + artifactInfo.setArtifactRepository(null); + + if (artifactInfo.getUserIdCreator() != null) { + log.error("creator uuid cannot be set ignoring"); + } + artifactInfo.setArtifactCreator(user.getUserId()); + + if (artifactInfo.getUserIdLastUpdater() != null) { + log.error("userId of last updater cannot be set ignoring"); + } + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + if (artifactInfo.getCreatorFullName() != null) { + log.error("creator Full name cannot be set ignoring"); + } + String fullName = user.getFirstName() + " " + user.getLastName(); + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getUpdaterFullName() != null) { + log.error("updater Full name cannot be set ignoring"); + } + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getCreationDate() != null) { + log.error("Creation Date cannot be set ignoring"); + } + long time = System.currentTimeMillis(); + artifactInfo.setCreationDate(time); + + if (artifactInfo.getLastUpdateDate() != null) { + log.error("Last Update Date cannot be set ignoring"); + } + artifactInfo.setLastUpdateDate(time); + + if (artifactInfo.getEsId() != null) { + log.error("es id cannot be set ignoring"); + } + artifactInfo.setEsId(null); + + } + + + private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) { + String id = artifactId; + if (artifactId == null || artifactId.isEmpty()) { + String uniqueId = null; + if (interfaceName != null && operationName != null) { + uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo + .getArtifactLabel()); + } + else { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()); + } + artifactInfo.setUniqueId(uniqueId); + artifactInfo.setEsId(uniqueId); + id = uniqueId; + } + else { + artifactInfo.setUniqueId(artifactId); + artifactInfo.setEsId(artifactId); + } + return id; + } + + private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { + if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { + BeEcompErrorManager.getInstance() + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); + } + + boolean artifactTypeExist = false; + Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null; + ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); + + if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { + allArtifactTypes = getDeploymentArtifactTypes(parentType); + } + else { + + allArtifactTypes = elementOperation.getAllArtifactTypes(); + } + if (allArtifactTypes.isRight()) { + BeEcompErrorManager.getInstance() + .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes + .right() + .value() + .name()); + log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right() + .value()); + return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); + } + + for (ArtifactType type : allArtifactTypes.left().value()) { + if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) { + artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase()); + artifactTypeExist = true; + break; + } + } + + if (!artifactTypeExist) { + BeEcompErrorManager.getInstance() + .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo + .getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); + log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + + return Either.left(ActionStatus.OK); + } + + private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { + + Map<String, ArtifactTypeConfig> deploymentArtifacts ; + List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); + + if (parentType.equals(NodeTypeEnum.Service)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts(); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); + } + else { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts(); + } + if (deploymentArtifacts != null) { + for (String artifactType : deploymentArtifacts.keySet()) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return Either.left(artifactTypes); + } + else { + return Either.right(ActionStatus.GENERAL_ERROR); + } + + } + + private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD)); + } + return Either.left(true); + + } + + private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) { + if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); + } + + String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName()); + if (normalizeFileName == null || normalizeFileName.isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); + } + artifactInfo.setArtifactName(normalizeFileName); + + if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH))); + } + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { + log.info("artifact type is missing operation ignored"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); + } + + if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { + log.info("artifact type cannot be changed operation ignored"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(true); + } + + private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (artifactInfo.getArtifactGroupType() == null) { + artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); + } + + else if (!currentArtifact.getArtifactGroupType() + .getType() + .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { + log.info("artifact group type cannot be changed. operation failed"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(artifactInfo); + } + + private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) { + + // on update if null add informational to current + if (currentArtifact.getArtifactGroupType() == null && type != null) { + currentArtifact.setArtifactGroupType(type); + } + + if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) { + log.error("artifact uniqid cannot be set ignoring"); + } + artifactInfo.setUniqueId(currentArtifact.getUniqueId()); + + if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef() + .equals(artifactInfo.getArtifactRef())) { + log.error("artifact ref cannot be set ignoring"); + } + artifactInfo.setArtifactRef(currentArtifact.getArtifactRef()); + + if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository() + .equals(artifactInfo.getArtifactRepository())) { + log.error("artifact repository cannot be set ignoring"); + } + artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository()); + + if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator() + .equals(artifactInfo.getUserIdCreator())) { + log.error("creator uuid cannot be set ignoring"); + } + artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator()); + + if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator() + .equals(artifactInfo.getArtifactCreator())) { + log.error("artifact creator cannot be set ignoring"); + } + artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator()); + + if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater() + .equals(artifactInfo.getUserIdLastUpdater())) { + log.error("userId of last updater cannot be set ignoring"); + } + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName() + .equals(artifactInfo.getCreatorFullName())) { + log.error("creator Full name cannot be set ignoring"); + } + artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName()); + + if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName() + .equals(artifactInfo.getUpdaterFullName())) { + log.error("updater Full name cannot be set ignoring"); + } + String fullName = user.getFirstName() + " " + user.getLastName(); + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate() + .equals(artifactInfo.getCreationDate())) { + log.error("Creation Date cannot be set ignoring"); + } + artifactInfo.setCreationDate(currentArtifact.getCreationDate()); + + if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate() + .equals(artifactInfo.getLastUpdateDate())) { + log.error("Last Update Date cannot be set ignoring"); + } + long time = System.currentTimeMillis(); + artifactInfo.setLastUpdateDate(time); + + if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) { + log.error("es id cannot be set ignoring"); + } + artifactInfo.setEsId(currentArtifact.getUniqueId()); + + if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName() + .equals(artifactInfo.getArtifactDisplayName())) { + log.error(" Artifact Display Name cannot be set ignoring"); + } + artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName()); + + if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi() + .equals(artifactInfo.getServiceApi())) { + log.debug("serviceApi cannot be set. ignoring."); + } + artifactInfo.setServiceApi(currentArtifact.getServiceApi()); + + if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType() + .equals(artifactInfo.getArtifactGroupType())) { + log.debug("artifact group cannot be set. ignoring."); + } + artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); + + artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion()); + + if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID() + .isEmpty() && !currentArtifact.getArtifactUUID() + .equals(artifactInfo.getArtifactUUID())) { + log.debug("artifact UUID cannot be set. ignoring."); + } + artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); + + if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo + .getHeatParameters() + .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) { + checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters()); + } + } + + private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) { + + Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters); + for (HeatParameterDefinition parameter : heatParameters) { + HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId()); + + if (currentParam != null) { + + if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) { + log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName()); + parameter.setName(currentParam.getName()); + } + if (parameter.getDefaultValue() != null && !parameter.getDefaultValue() + .equalsIgnoreCase(currentParam.getDefaultValue())) { + log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); + parameter.setDefaultValue(currentParam.getDefaultValue()); + } + if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) { + log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType()); + parameter.setType(currentParam.getType()); + } + if (parameter.getDescription() != null && !parameter.getDescription() + .equalsIgnoreCase(currentParam.getDescription())) { + log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription()); + parameter.setDescription(currentParam.getDescription()); + } + + // check and set current value + if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) { + log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue()); + parameter.setCurrentValue(currentParam.getDefaultValue()); + } + } + } + } + + private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) { + + Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>(); + for (HeatParameterDefinition param : currentParameters) { + currentParamsMap.put(param.getUniqueId(), param); + } + return currentParamsMap; + } + + private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) { + if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) { + log.debug("Artifact url cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL)); + } + artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase()); + + if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL)); + } + if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH))); + } + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) { + if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) { + log.debug("Artifact description cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION)); + } + String description = artifactInfo.getDescription(); + description = ValidationUtils.removeNoneUtf8Chars(description); + description = ValidationUtils.normaliseWhitespace(description); + description = ValidationUtils.stripOctets(description); + description = ValidationUtils.removeHtmlTagsOnly(description); + if (!ValidationUtils.validateIsEnglish(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String + .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH))); + } + artifactInfo.setDescription(description); + return Either.left(true); + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload, + ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) { + ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); + String prevArtifactId = null; + String currArtifactId = artifactId; + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + Either<ArtifactDefinition, Operation> insideEither = null; + + if (artifactData == null) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to create artifact object for ES."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + return resultOp; + } + log.trace("Try to update entry on graph"); + String artifactUniqueId = null; + ArtifactDefinition artifactDefinition = artifactInfo; + StorageOperationStatus error; + + boolean isLeft; + if (!(interfaceType != null && operationName != null)) { + log.debug("Enty on graph is updated. Update artifact in ES"); + boolean res = true; + // Changing previous and current artifactId for auditing + prevArtifactId = currArtifactId; + currArtifactId = artifactDefinition.getUniqueId(); + + NodeTypeEnum convertParentType = convertParentType(componentType); + + if (decodedPayload == null) { + if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { + Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition + .getEsId()); + if (artifactFromCassandra.isRight()) { + log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); + error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right() + .value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + return resultOp; + } + // clone data to new artifact + artifactData.setData(artifactFromCassandra.left().value().getData()); + artifactData.setId(artifactFromCassandra.left().value().getId()); + } + } + else { + if (artifactDefinition.getEsId() == null) { + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactData.setId(artifactDefinition.getUniqueId()); + } + } + + Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent + .getUniqueId(), artifactId, convertParentType, parentId); + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + artifactDefinition = result.left().value(); + String artifactType = artifactInfo.getArtifactType(); + if (NodeTypeEnum.Resource == convertParentType + && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) + && !artifactUniqueId.equals(artifactId)) { + // need to update the generated id in heat env + Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts(); + Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet() + .stream() + .filter(a -> a.getValue() + .getGeneratedFromId() != null && a + .getValue() + .getGeneratedFromId() + .equals(artifactId)) + .findFirst(); + if (findFirst.isPresent()) { + ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); + artifactEnvInfo.setArtifactChecksum(null); + artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId); + } + } + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + else { + error = result.right().value(); + } + if (isLeft) { + + // create new entry in ES + res = true; + if (artifactData.getData() != null) { + if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) { + artifactData.setId(artifactDefinition.getEsId()); + } + res = saveArtifacts(artifactData, parentId); + + } + } + + if (res) { + log.debug("Artifact saved into ES - {}", artifactUniqueId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + + return resultOp; + } + + private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) { + log.trace("Starting payload handling"); + byte[] payload = artifactInfo.getPayloadData(); + byte[] decodedPayload = null; + + if (payload != null && payload.length != 0) { + // the generated artifacts were already decoded by the handler + decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload); + if (decodedPayload.length == 0) { + log.debug("Failed to decode the payload."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + + String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload); + artifactInfo.setArtifactChecksum(checkSum); + log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum); + + // Specific payload validations of different types + Either<Boolean, ResponseFormat> isValidPayload = Either.left(true); + if (isDeploymentArtifact(artifactInfo)) { + log.trace("Starting deployment artifacts payload validation"); + String artifactType = artifactInfo.getArtifactType(); + if (ArtifactTypeEnum.HEAT.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { + isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType); + if (isValidPayload.isLeft()) { + isValidPayload = extractHeatParameters(artifactInfo); + } + } + else if (ArtifactTypeEnum.YANG_XML.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.VENDOR_LICENSE.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION + .getType() + .equalsIgnoreCase(artifactType)) { + isValidPayload = validateXmlPayload(decodedPayload, artifactType); + } + else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.VES_EVENTS.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS + .getType() + .equalsIgnoreCase(artifactType)) { + String artifactFileName = artifactInfo.getArtifactName(); + String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase(); + switch (fileExtension) { + case "xml": + isValidPayload = validateXmlPayload(decodedPayload, artifactType); + break; + case "json": + isValidPayload = validateJsonPayload(decodedPayload, artifactType); + break; + case "yml": + case "yaml": + isValidPayload = validateYmlPayload(decodedPayload, artifactType); + break; + default: + break; + } + } + } + if (isValidPayload.isRight()) { + ResponseFormat responseFormat = isValidPayload.right().value(); + return Either.right(responseFormat); + } + + } // null/empty payload is normal if called from metadata update ONLY. + // The validation of whether this is metadata/payload update case is + // currently done separately + else { + if (!isArtifactMetadataUpdate) { + log.debug("Payload is missing."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + return Either.right(responseFormat); + } + } + log.trace("Ended payload handling"); + return Either.left(decodedPayload); + } + + private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) { + // Basic YAML validation + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { + log.debug("Invalid YAML format"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); + return Either.right(responseFormat); + } + if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { + // HEAT specific YAML validation + DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class); + if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) { + log.debug("HEAT doesn't contain required \"heat_template_version\" section."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType); + return Either.right(responseFormat); + } + } + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) { + Either<Boolean, ResponseFormat> res = Either.left(true); + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { + log.debug("Invalid YAML format"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); + res = Either.right(responseFormat); + } + + return res; + } + + private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) { + boolean isXmlValid = isValidXml(payload); + if (!isXmlValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_XML, artifactType); + log.debug("Invalid XML content"); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) { + boolean isJsonValid = isValidJson(payload); + if (!isJsonValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_JSON, type); + log.debug("Invalid JSON content"); + return Either.right(responseFormat); + } + return Either.left(true); + } + + public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId, + boolean inTransaction) { + User user = new User(); + user.setUserId(userUserId); + Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata); + if (parent.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent + .right() + .value())); + return Either.right(responseFormat); + } + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent + .left() + .value(), + false, inTransaction); + if (handleDelete.isRight()) { + return Either.right(handleDelete.right().value()); + } + Either<ArtifactDefinition, Operation> result = handleDelete.left().value(); + return Either.left(result.right().value()); + + } + + private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) { + Operation op = new Operation(); + long time = System.currentTimeMillis(); + op.setCreationDate(time); + + String artifactName = artifactInfo.getArtifactName(); + artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName)); + + op.setImplementation(artifactInfo); + op.setLastUpdateDate(time); + return op; + } + + private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) { + String newArtifactName = operationName + "_" + artifactName; + log.trace("converting artifact name {} to {}", artifactName, newArtifactName); + return newArtifactName; + } + + // download by MSO + public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { + + // General validation + if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + artifactName = ValidationUtils.normalizeFileName(artifactName); + + // Resource validation + Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); + if (validateResourceNameAndVersion.isRight()) { + return Either.right(validateResourceNameAndVersion.right().value()); + } + + Resource resource = validateResourceNameAndVersion.left().value(); + String resourceId = resource.getUniqueId(); + + // Service validation + Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + log.debug("Deployment artifacts of resource {} are not found", resourceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + ArtifactDefinition deploymentArtifact = null; + + for (ArtifactDefinition artifactDefinition : artifacts.values()) { + if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName() + .equals(artifactName)) { + log.debug("Found deployment artifact {}", artifactName); + deploymentArtifact = artifactDefinition; + break; + } + } + + if (deploymentArtifact == null) { + log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + // Downloading the artifact + Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact); + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", artifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + // download by MSO + public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { + + // General validation + if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + artifactName = ValidationUtils.normalizeFileName(artifactName); + + // Service validation + Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + Service service = validateServiceNameAndVersion.left().value(); + + // ResourceInstance validation + Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName); + if (validateResourceInstance.isRight()) { + return Either.right(validateResourceInstance.right().value()); + } + + ComponentInstance resourceInstance = validateResourceInstance.left().value(); + + Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); + + final String finalArtifactName = artifactName; + Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); + + boolean hasDeploymentArtifacts = artifacts != null && artifacts.values() + .stream() + .anyMatch(filterArtifactByName); + ArtifactDefinition deployableArtifact; + + if (!hasDeploymentArtifacts) { + log.debug("Deployment artifact with name {} not found", artifactName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + log.debug("Found deployment artifact {}", artifactName); + deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get(); + // Downloading the artifact + Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact); + + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", artifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) { + + List<ComponentInstance> riList = service.getComponentInstances(); + for (ComponentInstance ri : riList) { + if (ri.getNormalizedName().equals(resourceInstanceName)) { + return Either.left(ri); + } + } + + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName)); + } + + private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) { + + Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); + if (serviceListBySystemName.isRight()) { + log.debug("Couldn't fetch any service with name {}", serviceName); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName + .right() + .value(), ComponentTypeEnum.SERVICE), serviceName)); + } + List<Service> serviceList = serviceListBySystemName.left().value(); + if (serviceList == null || serviceList.isEmpty()) { + log.debug("Couldn't fetch any service with name {}", serviceName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName)); + } + + Service foundService = null; + for (Service service : serviceList) { + if (service.getVersion().equals(serviceVersion)) { + log.trace("Found service with version {}", serviceVersion); + foundService = service; + break; + } + } + + if (foundService == null) { + log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE + .getValue(), serviceVersion)); + } + return Either.left(foundService); + } + + private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) { + + Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); + if (resourceListBySystemName.isRight()) { + log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName + .right() + .value()), resourceName)); + } + return Either.left(resourceListBySystemName.left().value()); + } + + public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { + // Validation + log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); + if (serviceName == null || serviceVersion == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); + + // Service validation + Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); + + // Looking for deployment or tosca artifacts + Service service = validateServiceNameAndVersion.left().value(); + + if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { + log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + } + + Optional<ArtifactDefinition> foundArtifactOptl = null; + + if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { + foundArtifactOptl = service.getDeploymentArtifacts().values().stream() + // filters artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + } + if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { + foundArtifactOptl = service.getToscaArtifacts().values().stream() + // filters TOSCA artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + } + if (!foundArtifactOptl.isPresent()) { + log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + } + log.debug("Found deployment artifact {}", normalizedArtifactName); + // Downloading the artifact + Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl + .get()); + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", normalizedArtifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { + log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); + Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); + if (artifactById.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); + log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); + } + ArtifactDefinition artifactDefinition = artifactById.left().value(); + if (artifactDefinition == null) { + log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + } + + return downloadArtifact(artifactDefinition); + } + + private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) { + boolean found = false; + Map<String, ArtifactDefinition> artifactsS = component.getArtifacts(); + if (artifactsS != null) { + for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts(); + if (!found && deploymentArtifactsS != null) { + for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts(); + if (!found && toscaArtifactsS != null) { + for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + switch (component.getComponentType()) { + case RESOURCE: + Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces(); + if (!found && interfaces != null) { + for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) { + Map<String, Operation> operations = entry.getValue().getOperationsMap(); + for (Map.Entry<String, Operation> entryOp : operations.entrySet()) { + if (entryOp.getValue().getImplementation() != null && entryOp.getValue() + .getImplementation() + .getUniqueId() + .equals(artifactId)) { + found = true; + break; + } + } + } + } + break; + case SERVICE: + Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts(); + if (!found && apiArtifacts != null) { + for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + break; + default: + + } + + return found; + } + + private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) { + + boolean found = false; + List<ComponentInstance> resourceInstances = component.getComponentInstances(); + ComponentInstance resourceInstance = null; + for (ComponentInstance ri : resourceInstances) { + if (ri.getUniqueId().equals(resourceInstanceId)) { + resourceInstance = ri; + break; + } + } + if (resourceInstance != null) { + Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); + if (artifacts != null) { + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + if (!found) { + artifacts = resourceInstance.getArtifacts(); + if (artifacts != null) { + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + } + } + return found; + } + + private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, + String containerComponentType) { + + ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); + componentForAudit.getNodeType(); + + Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade + .getToscaFullElement(componentId); + + if (componentResult.isRight()) { + ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); + log.debug("Service not found, serviceId {}", componentId); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); + return Either.right(responseFormat); + } + return Either.left(componentResult.left().value()); + } + + private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) { + Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + String uniqueId = component.getUniqueId(); + log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId); + handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right() + .value(), component + .getComponentType(), null); + return Either.right(canWork.right().value()); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { + + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) { + String role = user.getRole(); + if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + return Either.left(true); + } + + private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { + Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction); + + if (validateUserExists.isRight()) { + User user = new User(); + user.setUserId(userId); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right() + .value(), componentType, null); + return Either.right(validateUserExists.right().value()); + } + return Either.left(validateUserExists.left().value()); + } + + protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) { + AuditingActionEnum auditingAction = null; + switch (operation.getArtifactOperationEnum()) { + case CREATE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD; + break; + case UPDATE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE; + break; + case DELETE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE; + break; + case DOWNLOAD: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD; + break; + default: + break; + } + return auditingAction; + } + + private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) { + String esArtifactId = artifactDefinition.getEsId(); + Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactfromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {}", actionStatus); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition + .getArtifactDisplayName()); + + return Either.right(responseFormat); + } + + ESArtifactData esArtifactData = artifactfromES.left().value(); + byte[] data = esArtifactData.getDataAsArray(); + if (data == null) { + log.debug("Artifact data from ES is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName())); + } + String artifactName = artifactDefinition.getArtifactName(); + log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName); + return Either.left(new ImmutablePair<String, byte[]>(artifactName, data)); + } + + public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { + return new ESArtifactData(artifactInfo.getEsId(), artifactPayload); + } + + private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) { + CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); + + if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { + log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); + } + else { + log.info("Failed to save artifact {}.", artifactData.getId()); + return false; + } + return true; + } + + private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) { + return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE); + } + + private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) { + return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()); + } + + public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { + Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction); + if (user.isRight()) { + ResponseFormat responseFormat; + if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + else { + log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); + responseFormat = componentsUtils.getResponseFormat(user.right().value()); + } + return Either.right(responseFormat); + } + + ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user + .left() + .value(), groupType); + return Either.left(artifactDefinition); + } + + public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); + String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE); + String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); + + artifactInfo.setArtifactDisplayName(artifactName); + artifactInfo.setArtifactLabel(logicalName.toLowerCase()); + artifactInfo.setArtifactType(artifactType); + artifactInfo.setDescription(artifactDescription); + artifactInfo.setArtifactGroupType(groupType); + nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo); + + setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo); + + return artifactInfo; + } + + private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) { + String uniqueId = null; + + if (resourceId != null) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel() + .toLowerCase()); + artifactInfo.setUniqueId(uniqueId); + } + artifactInfo.setUserIdCreator(user.getUserId()); + String fullName = user.getFullName(); + artifactInfo.setUpdaterFullName(fullName); + + long time = System.currentTimeMillis(); + + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + artifactInfo.setMandatory(true); + } + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { + return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); + } + + public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { + return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); + } + + private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { + + byte[] payload = payloadStr.getBytes(); + + ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); + return Either.left(artifactData); + } + + /** + * @param artifactDefinition + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + String instanceId, boolean shouldLock, boolean inTransaction) { + String payload = generateHeatEnvPayload(artifactDefinition); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } + + public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, boolean inTransaction, String instanceId) { + String payload = generateHeatEnvPayload(artifactDefinition); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } + + private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { + if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) { List<ComponentInstance> componentInstances = component.getComponentInstances(); if (componentInstances != null) { - Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); + Optional<ComponentInstance> findFirst = componentInstances.stream() + .filter(ci -> ci.getUniqueId() + .equals(instanceId)) + .findFirst(); if (findFirst.isPresent()) { ComponentInstance relevantInst = findFirst.get(); - List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); + List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst + .getGroupInstances()); if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { updatedGroupInstances.forEach(gi -> { @@ -3643,426 +3813,496 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); if (status.isRight()) { log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils + .convertFromStorageResponse(status.right() + .value()), clonedBeforeGenerate.getArtifactDisplayName()); return Either.right(responseFormat); } } } } } - return Either.left(updatedArtDef); - } - - private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { - List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters(); - StringBuilder sb = new StringBuilder(); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append("parameters:\n"); - if (heatParameters != null) { - heatParameters.sort(Comparator.comparing(e -> e.getName())); - - List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>(); - - for (HeatParameterDefinition heatParameterDefinition : heatParameters) { - - String heatValue = heatParameterDefinition.getCurrentValue(); - if (!ValidationUtils.validateStringNotEmpty(heatValue)) { - heatValue = heatParameterDefinition.getDefaultValue(); - if (!ValidationUtils.validateStringNotEmpty(heatValue)) { - empltyHeatValues.add(heatParameterDefinition); - continue; - } - } - HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); - if (type != null) { - switch (type) { - case BOOLEAN: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n"); - break; - case NUMBER: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n"); - break; - case COMMA_DELIMITED_LIST: - case JSON: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n"); - break; - default: - String value = heatValue; - boolean starts = value.startsWith("\""); - boolean ends = value.endsWith("\""); - if (!(starts && ends)) { - starts = value.startsWith("'"); - ends = value.endsWith("'"); - if (!(starts && ends)) { - value = "\"" + value + "\""; - } - } - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value); - sb.append("\n"); - break; - - } - } - } - if (!empltyHeatValues.isEmpty()) { - empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); - empltyHeatValues.forEach(hv -> { - sb.append(" ").append(hv.getName()).append(":"); - HeatParameterType type = HeatParameterType.isValidType(hv.getType()); - if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { - sb.append(" \"\"").append("\n"); - } else { - sb.append(" ").append("\n"); - } - }); - } - } - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - - // DE265919 fix - String result = sb.toString().replaceAll("\\\\n", "\n"); - - return result; - } - - /** - * - * @param artifactDefinition - * @param payload - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, - User modifier, boolean shouldLock, String instanceId) { - return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), - () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); - - } - - public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, - User modifier, boolean shouldLock, String instanceId) { - return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, System::currentTimeMillis, - () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); - - } - - protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) { - - log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) { - - log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get(); - ESArtifactData artifactData = null; - - if (artifactDataRes.isLeft()) { - artifactData = artifactDataRes.left().value(); - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(artifactDataRes.right().value()); - } - String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray()); - String oldCheckSum; - String esArtifactId = artifactDefinition.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactfromES; - ESArtifactData esArtifactData; - if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { - log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId); - artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus.name(), esArtifactId); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName())); - } - esArtifactData = artifactfromES.left().value(); - oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray()); - } else { - oldCheckSum = artifactDefinition.getArtifactChecksum(); - - } - Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null; - - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null); - return Either.right(lockComponent.right().value()); - } - } - try { - if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { - - artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); - log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - if (updateArifactDefinitionStatus.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId()); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - } - } else { - - oldCheckSum = artifactDefinition.getArtifactChecksum(); - artifactDefinition.setArtifactChecksum(newCheckSum); - // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); - - log.trace("Update Payload ", artifactDefinition.getEsId()); - } - if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { - - artifactDefinition = updateArifactDefinitionStatus.left().value(); - artifactData.setId(artifactDefinition.getUniqueId()); - CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - - if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { - titanDao.commit(); - log.debug("Artifact Saved In ES {}", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - } else { - titanDao.rollback(); - log.info("Failed to save artifact {}.", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - } - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.debug("Failed To update artifact {}", artifactData.getId()); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - - } - } finally { - if (shouldLock) { - graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType()); - } - } - } - - return Either.left(artifactDefinition); - } - - - public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) { - return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(), - artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters()); - - } - - public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent, - List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) { - - Map<String, Object> json = new HashMap<String, Object>(); - if (artifactId != null && !artifactId.isEmpty()) - json.put(Constants.ARTIFACT_ID, artifactId); - - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_TYPE, artifactType); - json.put(Constants.ARTIFACT_DESCRIPTION, description); - - if (artifactContent != null) { - String encodedPayload = new String(artifactContent); - - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - log.debug("payload is encoded. perform decode"); - encodedPayload = Base64.encodeBase64String(artifactContent); - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - } - // } - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); - json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() - : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() - : heatParameters); - return json; - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { - - String jsonStr = gson.toJson(json); - ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; - String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, - artifactDefinitionFromJson, null, jsonStr, null, null, null, user, containerComponent, false, false, true); - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - return Either.left(uploadArtifactToService.left().value()); - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); - // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId); - ArtifactDefinition currArtifact = artifactInfo; - - if (origMd5 != null) { - Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance); - if (deploymentValidationResult.isRight()) { - ResponseFormat responseFormat = deploymentValidationResult.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - - // lock resource - if (shouldLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); - return resultOp; - - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - if (false == inTransaction) - titanDao.rollback(); - } else { - log.debug("all changes committed"); - if (false == inTransaction) - titanDao.commit(); - } - if (shouldLock) - componentType = parent.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, String origMd5) { - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - /* - * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value(); - */ - Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); - if (getRI.isRight()) { - return Either.right(getRI.right().value()); - } - ComponentInstance ri = getRI.left().value(); - Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user); - if (getArtifactRes.isRight()) { - return Either.right(getArtifactRes.right().value()); - } - ArtifactDefinition currArtifact = getArtifactRes.left().value(); - - if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters(); - List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters(); - new ArrayList<HeatParameterDefinition>(); - - // upload - if (origMd5 != null) { - Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams, - updatedHeatEnvParams, currArtifact.getArtifactName()); - if (uploadParamsValidationResult.isRight()) { - ResponseFormat responseFormat = uploadParamsValidationResult.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - artifactInfo.setListHeatParameters(updatedHeatEnvParams); - } - - Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType()); - if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { - // fill reduced heat env parameters List for updating - replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); - currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); - currArtifact.setListHeatParameters(currentHeatEnvParams); - - Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); - if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId()); - if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - } - insideEither = Either.left(currArtifact); - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName()); - return resultOp; - } - - private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) { - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + return Either.left(updatedArtDef); + } + + private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { + List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters(); + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append("parameters:\n"); + if (heatParameters != null) { + heatParameters.sort(Comparator.comparing(e -> e.getName())); + + List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters) { + + String heatValue = heatParameterDefinition.getCurrentValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + heatValue = heatParameterDefinition.getDefaultValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + empltyHeatValues.add(heatParameterDefinition); + continue; + } + } + HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); + if (type != null) { + switch (type) { + case BOOLEAN: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(Boolean.parseBoolean(heatValue)) + .append("\n"); + break; + case NUMBER: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(new BigDecimal(heatValue).toPlainString()) + .append("\n"); + break; + case COMMA_DELIMITED_LIST: + case JSON: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(heatValue) + .append("\n"); + break; + default: + String value = heatValue; + boolean starts = value.startsWith("\""); + boolean ends = value.endsWith("\""); + if (!(starts && ends)) { + starts = value.startsWith("'"); + ends = value.endsWith("'"); + if (!(starts && ends)) { + value = "\"" + value + "\""; + } + } + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(value); + sb.append("\n"); + break; + + } + } + } + if (!empltyHeatValues.isEmpty()) { + empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); + empltyHeatValues.forEach(hv -> { + sb.append(" ").append(hv.getName()).append(":"); + HeatParameterType type = HeatParameterType.isValidType(hv.getType()); + if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv + .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { + sb.append(" \"\"").append("\n"); + } + else { + sb.append(" ").append("\n"); + } + }); + } + } + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + + // DE265919 fix + return sb.toString().replaceAll("\\\\n", "\n"); + } + + /** + * @param artifactDefinition + * @param payload + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition + .getHeatParamsUpdateDate(), + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); + + } + + public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis, + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); + + } + + protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) { + + log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition + .getEsId()); + if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition + .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) { + + log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); + Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get(); + ESArtifactData artifactData = null; + + if (artifactDataRes.isLeft()) { + artifactData = artifactDataRes.left().value(); + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(artifactDataRes.right().value()); + } + String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray()); + String oldCheckSum; + String esArtifactId = artifactDefinition.getEsId(); + Either<ESArtifactData, CassandraOperationStatus> artifactfromES; + ESArtifactData esArtifactData; + if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { + log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId); + artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactfromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName())); + } + esArtifactData = artifactfromES.left().value(); + oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray()); + } + else { + oldCheckSum = artifactDefinition.getArtifactChecksum(); + + } + Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null; + + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: "); + if (lockComponent.isRight()) { + handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition + .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null); + return Either.right(lockComponent.right().value()); + } + } + try { + if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { + + artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component + .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition + .getArtifactType(), artifactDefinition.getEsId()); + if (updateArifactDefinitionStatus.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus + .right() + .value()), artifactDefinition.getArtifactDisplayName()); + log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId()); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + } + } + else { + + oldCheckSum = artifactDefinition.getArtifactChecksum(); + artifactDefinition.setArtifactChecksum(newCheckSum); + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition + .getArtifactType(), artifactDefinition.getEsId()); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component + .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + + log.trace("Update Payload ", artifactDefinition.getEsId()); + } + if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { + + artifactDefinition = updateArifactDefinitionStatus.left().value(); + artifactData.setId(artifactDefinition.getUniqueId()); + CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); + + if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { + if (!inTransaction) { + titanDao.commit(); + } + log.debug("Artifact Saved In ES {}", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + } + else { + if (!inTransaction) { + titanDao.rollback(); + } + log.info("Failed to save artifact {}.", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + } + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus + .right() + .value()), artifactDefinition.getArtifactDisplayName()); + log.debug("Failed To update artifact {}", artifactData.getId()); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + + } + } + finally { + if (shouldLock) { + graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType() + .getNodeType()); + } + } + } + + return Either.left(artifactDefinition); + } + + + public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) { + return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef + .getArtifactLabel(), artifactDef.getArtifactDisplayName(), + artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters()); + + } + + public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent, + List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) { + + Map<String, Object> json = new HashMap<String, Object>(); + if (artifactId != null && !artifactId.isEmpty()) { + json.put(Constants.ARTIFACT_ID, artifactId); + } + + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_TYPE, artifactType); + json.put(Constants.ARTIFACT_DESCRIPTION, description); + + if (artifactContent != null) { + log.debug("payload is encoded. perform decode"); + String encodedPayload = Base64.encodeBase64String(artifactContent); + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + } + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); + json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() + : updatedRequiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e + .getType() + .equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()) + .collect(Collectors.toList())); + json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() + : heatParameters); + return json; + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { + + String jsonStr = gson.toJson(json); + ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, + artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true); + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + return Either.left(uploadArtifactToService.left().value()); + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + convertParentType(componentType); + String parentId = parent.getUniqueId(); + ArtifactDefinition currArtifact = artifactInfo; + + if (origMd5 != null) { + Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { + Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance); + if (deploymentValidationResult.isRight()) { + ResponseFormat responseFormat = deploymentValidationResult.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + else { // duplicate + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + + // lock resource + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + try { + resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); + return resultOp; + + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + if (!inTransaction) { + titanDao.rollback(); + } + } + else { + log.debug("all changes committed"); + if (!inTransaction) { + titanDao.commit(); + } + } + if (shouldLock) { + componentType = parent.getComponentType(); + } + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); + } + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, String origMd5) { + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; + Either<ArtifactDefinition, Operation> insideEither = null; + Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); + if (getRI.isRight()) { + return Either.right(getRI.right().value()); + } + ComponentInstance ri = getRI.left().value(); + Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user); + if (getArtifactRes.isRight()) { + return Either.right(getArtifactRes.right().value()); + } + ArtifactDefinition currArtifact = getArtifactRes.left().value(); + + if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType() + .equals(ArtifactTypeEnum.HEAT_VOL + .getType()) || currArtifact + .getArtifactType() + .equals(ArtifactTypeEnum.HEAT_NET.getType())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters(); + List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters(); + new ArrayList<HeatParameterDefinition>(); + + // upload + if (origMd5 != null) { + Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri + .getName(), currentHeatEnvParams, + updatedHeatEnvParams, currArtifact.getArtifactName()); + if (uploadParamsValidationResult.isRight()) { + ResponseFormat responseFormat = uploadParamsValidationResult.right().value(); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + artifactInfo.setListHeatParameters(updatedHeatEnvParams); + } + + Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV + .getType()); + if (validateAndConvertHeatParamers.isRight()) { + ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { + // fill reduced heat env parameters List for updating + replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); + currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + currArtifact.setListHeatParameters(currentHeatEnvParams); + + Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent + .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); + if (updateArifactRes.isRight()) { + log.debug("Failed to update artifact on graph - {}", artifactId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes + .right() + .value())); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left() + .value() + .getUniqueId(), parent.getUniqueId()); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + } + insideEither = Either.left(currArtifact); + resultOp = Either.left(insideEither); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri + .getName()); + return resultOp; + } + + private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) { + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { String paramName = heatEnvParam.getName(); for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { if (paramName.equalsIgnoreCase(currHeatParam.getName())) { @@ -4071,1001 +4311,1144 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) { - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null; - Either<ArtifactDefinition, Operation> insideEither = null; - /* - * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value(); - */ - String currentHeatId = currHeatArtifact.getUniqueId(); - - String esArtifactId = currHeatArtifact.getEsId(); - Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {}", actionStatus.name()); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName())); - } - - ESArtifactData esArtifactData = artifactfromES.left().value(); - ArtifactDefinition updatedHeatArt = currHeatArtifact; - - List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); - List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); - List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { - - String paramName; - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue == null) - updatedParamValue = heatEnvParam.getDefaultValue(); - HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); - if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); - - } - currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); - newHeatEnvParams.add(currHeatParam); - break; - } - } - } - if (!newHeatEnvParams.isEmpty()) { - currHeatArtifact.setListHeatParameters(currentHeatEnvParams); - Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); - - if (operationStatus.isRight()) { - log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value())); - return Either.right(responseFormat); - - } - updatedHeatArt = operationStatus.left().value(); - boolean res = true; - if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) - esArtifactData.setId(updatedHeatArt.getEsId()); - res = saveArtifacts(esArtifactData, parent.getUniqueId(), false); - - if (res) { - log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null); - // resultOp = Either.left(result.left().value()); - // return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - // return resultOp; - } - - insideEither = Either.left(updatedHeatArt); - } - } - Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact; - if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { - artifactEnvInfo.setArtifactChecksum(null); - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId); - } else { - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType()); - - } - if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { - ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType); - if (result != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(result); - return Either.right(responseFormat); - } - } - - if (updatedHeatEnvParams.isEmpty()) { - return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType); - } - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return resultOp; - - } - - private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); - } - - - private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) { - StorageOperationStatus error = StorageOperationStatus.OK; - log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId()); - List<GroupInstance> groupsInstances = ri.getGroupInstances(); - // List<GroupInstance> associatedGroups = null; - List<String> groupInstancesId = null; - if (groupsInstances != null && !groupsInstances.isEmpty()) { - groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList()); - } - if (groupInstancesId != null && !groupInstancesId.isEmpty()) { - // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId())); - toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); - } - return error; - - } - - public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType, - String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) { - - if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); - return Either.right(responseFormat); - } - - for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) { - String paramName = uploadedHeatParam.getName(); - boolean isExistsInHeat = false; - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - isExistsInHeat = true; - uploadedHeatParam.setType(currHeatParam.getType()); - uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue()); - uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue()); - uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId()); - break; - } - } - if (!isExistsInHeat) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); - return Either.right(responseFormat); - } - } - return Either.left(updatedHeatEnvParams); - } - - private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { - ResponseFormat responseFormat = null; - List<ComponentInstance> ris = component.getComponentInstances(); - for (ComponentInstance ri : ris) { - if (riID.equals(ri.getUniqueId())) { - return Either.left(ri); - } - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID); - log.debug("Resource Instance not found, resourceInstanceId {}", riID); - handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null); - return Either.right(responseFormat); - } - - private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { - ResponseFormat responseFormat = null; - Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts(); - for (ArtifactDefinition artifact : rtifactsMap.values()) { - if (artifactId.equals(artifact.getUniqueId())) { - return Either.left(artifact); - } - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId()); - handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName()); - return Either.right(responseFormat); - } - - public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) { - ArtifactDefinition ret; - if (eitherArtifact.isLeft()) { - ret = eitherArtifact.left().value(); - } else { - ret = eitherArtifact.right().value().getImplementationArtifact(); - } - return ret; - } - - /** - * downloads artifact of component by UUIDs - * - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param auditAdditionalParam - * @return - */ - public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<byte[], ResponseFormat> result; - byte[] downloadedArtifact = null; - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - /** - * downloads an artifact of resource instance of component by UUIDs - * - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param auditAdditionalParam - * @return - */ - public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<byte[], ResponseFormat> result; - byte[] downloadedArtifact = null; - ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - if (errorWrapper.isEmpty()) { - downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - /** - * uploads an artifact to a component by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param additionalParams - * @param operation - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams, - ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult; - ArtifactDefinition uploadArtifact = null; - Component component = null; - String componentId = null; - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - uploadArtifact = actionResult.left().value().left().value(); - uploadArtifactResult = Either.left(uploadArtifact); - } else { - uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); - return uploadArtifactResult; - } - - /** - * upload an artifact to a resource instance by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param additionalParams - * @param operation - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, - Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition uploadArtifact = null; - Component component = null; - String componentInstanceId; - String componentId; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ImmutablePair<Component, ComponentInstance> componentRiPair = null; - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - uploadArtifact = actionResult.left().value().left().value(); - uploadArtifactResult = Either.left(uploadArtifact); - } else { - uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); - return uploadArtifactResult; - } - - /** - * updates an artifact on a component by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, - Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); - - } else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); - return updateArtifactResult; - } - - /** - * updates an artifact on a resource instance by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { - - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; - Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ImmutablePair<Component, ComponentInstance> componentRiPair = null; - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); - } else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); - return updateArtifactResult; - } - - /** - * deletes an artifact on a component by UUID - * - * @param request - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams, - ArtifactOperationInfo operation) { - - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); - } else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); - return deleteArtifactResult; - } - - /** - * deletes an artifact from a resource instance by UUID - * - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { - - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; - Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - ImmutablePair<Component, ComponentInstance> componentRiPair = null; - Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); - } else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); - return deleteArtifactResult; - } - - private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) { - String artifactId = null; - ArtifactDefinition foundArtifact = null; - if (instance.getDeploymentArtifacts() != null) { - foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); - } - if (foundArtifact == null && instance.getArtifacts() != null) { - foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); - } - if (foundArtifact == null) { - log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); - } else { - artifactId = foundArtifact.getUniqueId(); - } - return artifactId; - } - - @SuppressWarnings("unchecked") - public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, - Map<String, String> existingEnvVersions) { - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - if (deploymentResourceArtifacts == null) { - log.debug("no deployment artifacts are configured for generated artifacts"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType); - if (placeHolderData == null) { - log.debug("no env type {} are configured for generated artifacts", envType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); - if (createArtifactPlaceHolder.isRight()) { - return Either.right(createArtifactPlaceHolder.right().value()); - } - ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); - artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); - artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); - artifactHeatEnv.setTimeout(0); - buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData); - // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow - handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); - ArtifactDefinition heatEnvPlaceholder; - // Evg : for resource instance artifact will be added later as block with other env artifacts from BL - if (parentType != NodeTypeEnum.ResourceInstance) { - Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component.getUniqueId(), parentType, parentId); - if (addHeatEnvArtifact.isRight()) { - log.debug("failed to create heat env artifact on resource instance"); - return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null)); - } - heatEnvPlaceholder = createArtifactPlaceHolder.left().value(); - } else { - heatEnvPlaceholder = artifactHeatEnv; - artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); - setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); - } - // audit - EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(heatEnvPlaceholder, "", heatEnvPlaceholder.getUniqueId()); - artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName); - ComponentTypeEnum componentType = component.getComponentType(); - if (parentType == NodeTypeEnum.ResourceInstance) { - componentType = ComponentTypeEnum.RESOURCE_INSTANCE; - } - componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields); - return Either.left(heatEnvPlaceholder); - } - - private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { - if (artifact.getListHeatParameters() == null) { - return; - } - List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>(); - for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) { + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp; + Either<ArtifactDefinition, Operation> insideEither = null; + String currentHeatId = currHeatArtifact.getUniqueId(); + + String esArtifactId = currHeatArtifact.getEsId(); + Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactFromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {}", actionStatus); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName())); + } + + ESArtifactData esArtifactData = artifactFromES.left().value(); + + ArtifactDefinition updatedHeatArt = currHeatArtifact; + + List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); + List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); + List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams + .isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) { + updatedParamValue = heatEnvParam.getDefaultValue(); + } + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV + .getType(), paramType.getType(), paramName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); + return Either.right(responseFormat); + + } + currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); + newHeatEnvParams.add(currHeatParam); + break; + } + } + } + if (!newHeatEnvParams.isEmpty()) { + currHeatArtifact.setListHeatParameters(currentHeatEnvParams); + Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent + .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); + + if (operationStatus.isRight()) { + log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus + .right() + .value())); + return Either.right(responseFormat); + + } + updatedHeatArt = operationStatus.left().value(); + boolean res = true; + if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) { + esArtifactData.setId(updatedHeatArt.getEsId()); + } + res = saveArtifacts(esArtifactData, parent.getUniqueId()); + + if (res) { + log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt + .getUniqueId(), responseFormat, componentType, null); + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt + .getUniqueId(), responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + + insideEither = Either.left(updatedHeatArt); + } + } + Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact; + if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { + artifactEnvInfo.setArtifactChecksum(null); + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt + .getUniqueId(), componentType.getNodeType(), componentId); + } + else { + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType + .getNodeType()); + + } + if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { + ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact + .left() + .value(), parent, componentType); + if (result != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(result); + return Either.right(responseFormat); + } + } + + if (updatedHeatEnvParams.isEmpty()) { + return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType); + } + resultOp = Either.left(insideEither); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); + return resultOp; + + } + + private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); + return Either.right(responseFormat); + } + + + private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) { + StorageOperationStatus error = StorageOperationStatus.OK; + log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId()); + List<GroupInstance> groupsInstances = ri.getGroupInstances(); + List<String> groupInstancesId = null; + if (groupsInstances != null && !groupsInstances.isEmpty()) { + groupInstancesId = groupsInstances.stream() + .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts() + .contains(artifactId)) + .map(GroupInstanceDataDefinition::getUniqueId) + .collect(Collectors.toList()); + } + if (groupInstancesId != null && !groupInstancesId.isEmpty()) { + toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); + } + return error; + + } + + public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType, + String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) { + + if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo + .getArtifactName(), currArtifactName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); + return Either.right(responseFormat); + } + + for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) { + String paramName = uploadedHeatParam.getName(); + boolean isExistsInHeat = false; + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + isExistsInHeat = true; + uploadedHeatParam.setType(currHeatParam.getType()); + uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue()); + uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue()); + uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId()); + break; + } + } + if (!isExistsInHeat) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); + return Either.right(responseFormat); + } + } + return Either.left(updatedHeatEnvParams); + } + + private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { + ResponseFormat responseFormat = null; + List<ComponentInstance> ris = component.getComponentInstances(); + for (ComponentInstance ri : ris) { + if (riID.equals(ri.getUniqueId())) { + return Either.left(ri); + } + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID); + log.debug("Resource Instance not found, resourceInstanceId {}", riID); + handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null); + return Either.right(responseFormat); + } + + private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { + ResponseFormat responseFormat = null; + Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts(); + for (ArtifactDefinition artifact : rtifactsMap.values()) { + if (artifactId.equals(artifact.getUniqueId())) { + return Either.left(artifact); + } + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId()); + handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri + .getName()); + return Either.right(responseFormat); + } + + public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) { + ArtifactDefinition ret; + if (eitherArtifact.isLeft()) { + ret = eitherArtifact.left().value(); + } + else { + ret = eitherArtifact.right().value().getImplementationArtifact(); + } + return ret; + } + + /** + * downloads artifact of component by UUIDs + * + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param auditAdditionalParam + * @return + */ + public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<byte[], ResponseFormat> result; + byte[] downloadedArtifact = null; + Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName()); + } + if (errorWrapper.isEmpty()) { + result = Either.left(downloadedArtifact); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + /** + * downloads an artifact of resource instance of component by UUIDs + * + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param auditAdditionalParam + * @return + */ + public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<byte[], ResponseFormat> result; + byte[] downloadedArtifact = null; + ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + if (errorWrapper.isEmpty()) { + downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance + .getName()); + } + if (errorWrapper.isEmpty()) { + result = Either.left(downloadedArtifact); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + /** + * uploads an artifact to a component by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param additionalParams + * @param operation + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams, + ArtifactOperationInfo operation) { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult; + ArtifactDefinition uploadArtifact = null; + Component component = null; + String componentId = null; + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + uploadArtifact = actionResult.left().value().left().value(); + uploadArtifactResult = Either.left(uploadArtifact); + } + else { + uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); + return uploadArtifactResult; + } + + /** + * upload an artifact to a resource instance by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param additionalParams + * @param operation + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, + Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult; + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + ArtifactDefinition uploadArtifact = null; + Component component = null; + String componentInstanceId; + String componentId; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ImmutablePair<Component, ComponentInstance> componentRiPair = null; + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + uploadArtifact = actionResult.left().value().left().value(); + uploadArtifactResult = Either.left(uploadArtifact); + } + else { + uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); + return uploadArtifactResult; + } + + /** + * updates an artifact on a component by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, + Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + ArtifactDefinition updateArtifact = null; + Component component = null; + String componentId = null; + String artifactId = null; + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + updateArtifact = actionResult.left().value().left().value(); + updateArtifactResult = Either.left(updateArtifact); + + } + else { + updateArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); + return updateArtifactResult; + } + + /** + * updates an artifact on a resource instance by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, + Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { + + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + ArtifactDefinition updateArtifact = null; + Component component = null; + String componentInstanceId = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ImmutablePair<Component, ComponentInstance> componentRiPair = null; + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); + } + if (errorWrapper.isEmpty()) { + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + updateArtifact = actionResult.left().value().left().value(); + updateArtifactResult = Either.left(updateArtifact); + } + else { + updateArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); + return updateArtifactResult; + } + + /** + * deletes an artifact on a component by UUID + * + * @param request + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams, + ArtifactOperationInfo operation) { + + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + ArtifactDefinition deleteArtifact = null; + Component component = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + deleteArtifact = actionResult.left().value().left().value(); + deleteArtifactResult = Either.left(deleteArtifact); + } + else { + deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); + return deleteArtifactResult; + } + + /** + * deletes an artifact from a resource instance by UUID + * + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, + Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) { + + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult; + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; + ArtifactDefinition deleteArtifact = null; + Component component = null; + String componentInstanceId = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + ImmutablePair<Component, ComponentInstance> componentRiPair = null; + Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); + } + if (errorWrapper.isEmpty()) { + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + deleteArtifact = actionResult.left().value().left().value(); + deleteArtifactResult = Either.left(deleteArtifact); + } + else { + deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); + return deleteArtifactResult; + } + + private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) { + String artifactId = null; + ArtifactDefinition foundArtifact = null; + if (instance.getDeploymentArtifacts() != null) { + foundArtifact = instance.getDeploymentArtifacts() + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); + } + if (foundArtifact == null && instance.getArtifacts() != null) { + foundArtifact = instance.getArtifacts() + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); + } + if (foundArtifact == null) { + log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + } + else { + artifactId = foundArtifact.getUniqueId(); + } + return artifactId; + } + + @SuppressWarnings("unchecked") + public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, + Map<String, String> existingEnvVersions) { + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getDeploymentResourceInstanceArtifacts(); + if (deploymentResourceArtifacts == null) { + log.debug("no deployment artifacts are configured for generated artifacts"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType); + if (placeHolderData == null) { + log.debug("no env type {} are configured for generated artifacts", envType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user + .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); + if (createArtifactPlaceHolder.isRight()) { + return Either.right(createArtifactPlaceHolder.right().value()); + } + ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); + artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); + artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); + artifactHeatEnv.setTimeout(0); + buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData); + // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow + handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); + ArtifactDefinition heatEnvPlaceholder; + // Evg : for resource instance artifact will be added later as block with other env artifacts from BL + if (parentType != NodeTypeEnum.ResourceInstance) { + Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component + .getUniqueId(), parentType, parentId); + if (addHeatEnvArtifact.isRight()) { + log.debug("failed to create heat env artifact on resource instance"); + return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact + .right() + .value(), false), "", null)); + } + heatEnvPlaceholder = createArtifactPlaceHolder.left().value(); + } + else { + heatEnvPlaceholder = artifactHeatEnv; + artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); + setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); + } + String artifactData = buildAuditingArtifactData(heatEnvPlaceholder); + ComponentTypeEnum componentType = component.getComponentType(); + if (parentType == NodeTypeEnum.ResourceInstance) { + componentType = ComponentTypeEnum.RESOURCE_INSTANCE; + } + componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType, + ResourceAuditData.newBuilder().build(), + ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), + parentName, null, artifactData, null); + return Either.left(heatEnvPlaceholder); + } + + private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { + if (artifact.getListHeatParameters() == null) { + return; + } + List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>(); + for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); heatEnvParameter.setCurrentValue(null); heatEnvParameters.add(heatEnvParameter); } - artifactDefinition.setListHeatParameters(heatEnvParameters); - } - - private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) { - String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); - String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); - String name = heatArtifact.getArtifactName(); - String fileName; - if (name == null) { - name = heatArtifact.getArtifactLabel(); - fileName = name + "." + envExtension; - } else { - fileName = name.replaceAll("." + heatExtension, "." + envExtension); - } - heatEnvArtifact.setArtifactName(fileName); - } - - private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) { - if (null != existingEnvVersions) { - String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); - if (null != prevVersion) { - heatEnvArtifact.setArtifactVersion(prevVersion); - } - } - } - - /** - * Handles Artifacts Request For Inner Component - * - * @param artifactsToHandle - * @param component - * @param user - * @param vfcsNewCreatedArtifacts - * @param operation - * @param shouldLock - * @param inTransaction - * @return - */ - public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts, - ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - - Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null; - ComponentTypeEnum componentType = component.getComponentType(); - List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>(); - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult; - String originData; - String origMd5; - try { - for (ArtifactDefinition artifact : artifactsToHandle) { - originData = buildJsonStringForCsarVfcArtifact(artifact); - origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData); - actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); - } - break; - } - uploadedArtifacts.add(actionResult.left().value().left().value()); - } - if (errorWrapper.isEmpty()) { - handleArtifactsResult = Either.left(uploadedArtifacts); - } else { - handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleArtifactsResult = Either.right(responseFormat); - log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); - } - return handleArtifactsResult; - } - - private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { - ComponentInstance componentInstance = null; - String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } - } - return componentInstance; - } - - private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { - - ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null; - String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } else { - relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); - } - return relatedComponentComponentInstancePair; - } - - private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { - ComponentInstance componentInstance; - ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null; - Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } else { - relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); - } - } - return relatedComponentComponentInstancePair; - } - - private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) { - - byte[] downloadedArtifact = null; - Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null; - List<ArtifactDefinition> artifactsList = null; - ArtifactDefinition deploymentArtifact = null; - if (artifacts != null && !artifacts.isEmpty()) { - artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList()); - } - if (artifactsList == null || artifactsList.isEmpty()) { - log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); - } - if (errorWrapper.isEmpty()) { - deploymentArtifact = artifactsList.get(0); - downloadArtifactEither = downloadArtifact(deploymentArtifact, null); - if (downloadArtifactEither.isRight()) { - log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName()); - errorWrapper.setInnerElement(downloadArtifactEither.right().value()); - } - } - if (errorWrapper.isEmpty()) { - log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); - downloadedArtifact = downloadArtifactEither.left().value().getRight(); - } - return downloadedArtifact; - } - - private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { - Component component = null; - Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } else { - component = getComponentRes.left().value(); - } - return component; - } - - private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { - Component component = null; - Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } else { - List<Component> value = getComponentRes.left().value(); - if (value.isEmpty()){ - log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid); - ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status)); - } else { - component = value.get(0); - } - } - return component; - } - - private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) { - String artifactId = null; - ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND; - StorageOperationStatus storageStatus; - ArtifactDefinition latestArtifact = null; - List<ArtifactDefinition> artifacts = null; - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); - if (getArtifactsRes.isRight()) { - storageStatus = getArtifactsRes.right().value(); - log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus); - if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) { - actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); - } - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - if (errorWrapper.isEmpty()) { - artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList()); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - } - if (errorWrapper.isEmpty()) { - latestArtifact = artifacts.stream().max((a1, a2) -> { - int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); - if (compareRes == 0) { - compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate()); - } - return compareRes; - }).get(); - if (latestArtifact == null) { - log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - } - if (errorWrapper.isEmpty()) { - artifactId = latestArtifact.getUniqueId(); - } - return artifactId; - } - - private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) { - - Component component = null; - Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false); - if (getUserRes.isRight()) { - log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value())); - } - if (errorWrapper.isEmpty()) { - User modifier = getUserRes.left().value(); - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); - Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus()); - errorWrapper.setInnerElement(checkoutRes.right().value()); - } else { - component = checkoutRes.left().value(); - } - } - return component; - } - - private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) { - if (artifact == null) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); - if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ""); - } - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); - } - } - - private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { - Map<String, Object> json = new HashMap<>(); - String artifactName = artifact.getArtifactName(); - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel()); - json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType()); - json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription()); - json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData()); - json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName()); - return gson.toJson(json); - } + artifactDefinition.setListHeatParameters(heatEnvParameters); + } + + private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) { + String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); + String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); + String name = heatArtifact.getArtifactName(); + String fileName; + if (name == null) { + name = heatArtifact.getArtifactLabel(); + fileName = name + "." + envExtension; + } + else { + fileName = name.replaceAll("." + heatExtension, "." + envExtension); + } + heatEnvArtifact.setArtifactName(fileName); + } + + private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) { + if (null != existingEnvVersions) { + String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); + if (null != prevVersion) { + heatEnvArtifact.setArtifactVersion(prevVersion); + } + } + } + + /** + * Handles Artifacts Request For Inner Component + * + * @param artifactsToHandle + * @param component + * @param user + * @param vfcsNewCreatedArtifacts + * @param operation + * @param shouldLock + * @param inTransaction + * @return + */ + public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + + Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null; + ComponentTypeEnum componentType = component.getComponentType(); + List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>(); + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult; + String originData; + String origMd5; + try { + for (ArtifactDefinition artifact : artifactsToHandle) { + originData = buildJsonStringForCsarVfcArtifact(artifact); + origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData); + actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact + .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component + .getName(), actionResult.right().value()); + errorWrapper.setInnerElement(actionResult.right().value()); + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); + } + break; + } + uploadedArtifacts.add(actionResult.left().value().left().value()); + } + if (errorWrapper.isEmpty()) { + handleArtifactsResult = Either.left(uploadedArtifacts); + } + else { + handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); + } + } + catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleArtifactsResult = Either.right(responseFormat); + log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); + } + return handleArtifactsResult; + } + + private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { + ComponentInstance componentInstance = null; + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); + Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) + .equals(normalizedName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + } + return componentInstance; + } + + private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { + + ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null; + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); + ComponentInstance componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) + .equals(normalizedName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + else { + relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); + } + return relatedComponentComponentInstancePair; + } + + private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) { + ComponentInstance componentInstance; + ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null; + Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + else { + relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); + } + } + return relatedComponentComponentInstancePair; + } + + private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) { + + byte[] downloadedArtifact = null; + Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null; + List<ArtifactDefinition> artifactsList = null; + ArtifactDefinition deploymentArtifact = null; + if (artifacts != null && !artifacts.isEmpty()) { + artifactsList = artifacts.values() + .stream() + .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); + } + if (artifactsList == null || artifactsList.isEmpty()) { + log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + } + if (errorWrapper.isEmpty()) { + deploymentArtifact = artifactsList.get(0); + downloadArtifactEither = downloadArtifact(deploymentArtifact); + if (downloadArtifactEither.isRight()) { + log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName()); + errorWrapper.setInnerElement(downloadArtifactEither.right().value()); + } + } + if (errorWrapper.isEmpty()) { + log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); + downloadedArtifact = downloadArtifactEither.left().value().getRight(); + } + return downloadedArtifact; + } + + private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { + Component component = null; + Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + else { + component = getComponentRes.left().value(); + } + return component; + } + + private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) { + Component component = null; + Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + else { + List<Component> value = getComponentRes.left().value(); + if (value.isEmpty()) { + log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid); + ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status)); + } + else { + component = value.get(0); + } + } + return component; + } + + private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) { + String artifactId = null; + ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND; + StorageOperationStatus storageStatus; + ArtifactDefinition latestArtifact = null; + List<ArtifactDefinition> artifacts = null; + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); + if (getArtifactsRes.isRight()) { + storageStatus = getArtifactsRes.right().value(); + log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus); + if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) { + actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); + } + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + if (errorWrapper.isEmpty()) { + artifacts = getArtifactsRes.left() + .value() + .values() + .stream() + .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); + if (artifacts == null || artifacts.isEmpty()) { + log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + } + if (errorWrapper.isEmpty()) { + latestArtifact = artifacts.stream().max((a1, a2) -> { + int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); + if (compareRes == 0) { + compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2 + .getLastUpdateDate()); + } + return compareRes; + }).get(); + if (latestArtifact == null) { + log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + } + if (errorWrapper.isEmpty()) { + artifactId = latestArtifact.getUniqueId(); + } + return artifactId; + } + + private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) { + + Component component = null; + Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false); + if (getUserRes.isRight()) { + log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes + .right() + .value()); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value())); + } + if (errorWrapper.isEmpty()) { + User modifier = getUserRes.left().value(); + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); + Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType + .getNodeType(), parentId, checkoutRes.right().value().getStatus()); + errorWrapper.setInnerElement(checkoutRes.right().value()); + } + else { + component = checkoutRes.left().value(); + } + } + return component; + } + + private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) { + if (artifact == null) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ""); + } + } + else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); + } + } + + private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { + Map<String, Object> json = new HashMap<>(); + String artifactName = artifact.getArtifactName(); + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel()); + json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType()); + json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription()); + json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData()); + json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName()); + return gson.toJson(json); + } + + @VisibleForTesting + void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) { + this.nodeTemplateOperation = nodeTemplateOperation; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index 2e14028338..6756108387 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -39,7 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; /** * This class holds the business logic relevant for attributes manipulation. @@ -50,256 +49,256 @@ import fj.data.Either; @Component("attributeBusinessLogic") public class AttributeBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_ATTRIBUTE = "CreateAttribute"; - private static final String UPDATE_ATTRIBUTE = "UpdateAttribute"; - private static final String DELETE_ATTRIBUTE = "DeleteAttribute"; - - private static Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class.getName()); - - /** - * Created attribute on the resource with resourceId - * - * @param resourceId - * @param newAttributeDef - * @param userId - * @return AttributeDefinition if created successfully Or ResponseFormat - */ - public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { - Either<PropertyDefinition, ResponseFormat> result = null; - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - try { - // Get the resource from DB - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute does not exist in resource - if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); - } - Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } - // validate property default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - - handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); - - // add the new attribute to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus from - // componentsUtils - Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - result = Either.left(either.left().value()); - - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - private boolean isAttributeExist(List<PropertyDefinition> attributes, String resourceUid, String propertyName) { - boolean isExist = false; - if (attributes != null) { - isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); - } - return isExist; - - } - - /** - * @param resourceId - * @param attributeId - * @param userId - * @return - */ - public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // Get the resource from DB - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - List<PropertyDefinition> attributes = resource.getAttributes(); - if (attributes == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); - } else { - Either<PropertyDefinition, ResponseFormat> result; - // verify attribute exist in resource - Optional<PropertyDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); - - if (optionalAtt.isPresent()) { - result = Either.left(optionalAtt.get()); - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); - } - return result; - } - - } - - /** - * Updates Attribute on resource - * - * @param resourceId - * @param attributeId - * @param newAttDef - * @param userId - * @return - */ - public Either<PropertyDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { - Either<PropertyDefinition, ResponseFormat> result = null; - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - try { - // Get the resource from DB - Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId); - if (eitherResource.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = eitherResource.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute exist in resource - Either<PropertyDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId); - if (eitherAttribute.isRight()) { - return Either.right(eitherAttribute.right().value()); - } - Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } - - // validate attribute default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value()); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - // add the new property to resource on graph - - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); - if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); - } - - - Either<PropertyDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); - - if (eitherAttUpdate.isRight()) { - log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); - return result; - } - - result = Either.left(eitherAttUpdate.left().value()); - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - /** - * Deletes Attribute on resource - * - * @param resourceId - * @param attributeId - * @param userId - * @return - */ - public Either<PropertyDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) { - - Either<PropertyDefinition, ResponseFormat> result = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - try { - // Get the resource from DB - Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId); - if (eitherResource.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = eitherResource.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute exist in resource - Either<PropertyDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId); - if (eitherAttributeExist.isRight()) { - return Either.right(eitherAttributeExist.right().value()); - } - String attributeName = eitherAttributeExist.left().value().getName(); - - // delete attribute of resource from graph - StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); - if (eitherAttributeDelete != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); - return result; - } - - result = Either.left(eitherAttributeExist.left().value()); - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - } + private static final String CREATE_ATTRIBUTE = "CreateAttribute"; + private static final String UPDATE_ATTRIBUTE = "UpdateAttribute"; + private static final String DELETE_ATTRIBUTE = "DeleteAttribute"; + + private static final Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class); + + /** + * Created attribute on the resource with resourceId + * + * @param resourceId + * @param newAttributeDef + * @param userId + * @return AttributeDefinition if created successfully Or ResponseFormat + */ + public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { + Either<PropertyDefinition, ResponseFormat> result = null; + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + try { + // Get the resource from DB + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute does not exist in resource + if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); + } + Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + if (eitherAllDataTypes.isRight()) { + return Either.right(eitherAllDataTypes.right().value()); + } + // validate property default values + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + + handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + + // add the new attribute to resource on graph + // need to get StorageOpaerationStatus and convert to ActionStatus from + // componentsUtils + Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + result = Either.left(either.left().value()); + + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + private boolean isAttributeExist(List<PropertyDefinition> attributes, String resourceUid, String propertyName) { + boolean isExist = false; + if (attributes != null) { + isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); + } + return isExist; + + } + + /** + * @param resourceId + * @param attributeId + * @param userId + * @return + */ + public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + // Get the resource from DB + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + List<PropertyDefinition> attributes = resource.getAttributes(); + if (attributes == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); + } else { + Either<PropertyDefinition, ResponseFormat> result; + // verify attribute exist in resource + Optional<PropertyDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); + + if (optionalAtt.isPresent()) { + result = Either.left(optionalAtt.get()); + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); + } + return result; + } + + } + + /** + * Updates Attribute on resource + * + * @param resourceId + * @param attributeId + * @param newAttDef + * @param userId + * @return + */ + public Either<PropertyDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { + Either<PropertyDefinition, ResponseFormat> result = null; + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + try { + // Get the resource from DB + Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId); + if (eitherResource.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = eitherResource.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute exist in resource + Either<PropertyDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId); + if (eitherAttribute.isRight()) { + return Either.right(eitherAttribute.right().value()); + } + Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + if (eitherAllDataTypes.isRight()) { + return Either.right(eitherAllDataTypes.right().value()); + } + + // validate attribute default values + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value()); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + // add the new property to resource on graph + + StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); + if (validateAndUpdateAttribute != StorageOperationStatus.OK) { + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); + } + + + Either<PropertyDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); + + if (eitherAttUpdate.isRight()) { + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); + return result; + } + + result = Either.left(eitherAttUpdate.left().value()); + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + /** + * Deletes Attribute on resource + * + * @param resourceId + * @param attributeId + * @param userId + * @return + */ + public Either<PropertyDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) { + + Either<PropertyDefinition, ResponseFormat> result = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + try { + // Get the resource from DB + Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId); + if (eitherResource.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = eitherResource.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute exist in resource + Either<PropertyDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId); + if (eitherAttributeExist.isRight()) { + return Either.right(eitherAttributeExist.right().value()); + } + String attributeName = eitherAttributeExist.left().value().getName(); + + // delete attribute of resource from graph + StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); + if (eitherAttributeDelete != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); + return result; + } + + result = Either.left(eitherAttributeExist.left().value()); + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index 14c451a3b0..e401cb14f5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - +import com.google.gson.JsonElement; +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -40,18 +37,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.IPropertyInputCommon; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; @@ -60,6 +49,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; @@ -78,696 +68,716 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.JsonElement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Function; -import fj.data.Either; +import static org.apache.commons.collections.CollectionUtils.isEmpty; public abstract class BaseBusinessLogic { - @Autowired - protected ComponentsUtils componentsUtils; - - @Autowired - protected IUserBusinessLogic userAdmin; - - @Autowired - protected IGraphLockOperation graphLockOperation; - - @Autowired - protected TitanDao titanDao; - - @Autowired - protected TitanGenericDao titanGenericDao; - - @Autowired - protected IElementOperation elementDao; - - @Autowired - protected IGroupOperation groupOperation; - - @Autowired - protected IGroupInstanceOperation groupInstanceOperation; - - @Autowired - protected IGroupTypeOperation groupTypeOperation; - - /*@Autowired - protected IArtifactOperation artifactOperation;*/ - @javax.annotation.Resource - protected ArtifactsOperations artifactToscaOperation; - -// @Autowired -// protected IAttributeOperation attributeOperation; - - @Autowired - protected PropertyOperation propertyOperation; - - @Autowired - protected ApplicationDataTypeCache applicationDataTypeCache; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } - - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } - - public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { - this.graphLockOperation = graphLockOperation; - } - - public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { - this.toscaOperationFacade = toscaOperationFacade; - } - - - private static Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class.getName()); - - public static final String EMPTY_VALUE = null; - - protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) { - String userId = user.getUserId(); - - if (StringUtils.isEmpty(userId)) { - log.debug("User header is missing "); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - return Either.right(responseFormat); - } - return Either.left(user); - } - - protected Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { - return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); - } - - protected void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) { - Either<User, ResponseFormat> resp = validateUserExists(userId, ecompErrorContext, false); - if (resp.isRight()) { - errorWrapper.setInnerElement(resp.right().value()); - } - } - - public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) { - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("validateUserExists - not authorized user, userId {}", userId); - Either.right(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("validateUserExists - failed to authorize user, userId {}", userId); - } - log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); - return Either.right(eitherCreator.right().value()); - } - return Either.left(eitherCreator.left().value()); - } - - public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, inTransaction); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - ResponseFormat responseFormat; - if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - if (log.isDebugEnabled()) - log.debug("validateUserExists - not authorized user, userId {}", userId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - if (log.isDebugEnabled()) - log.debug("validateUserExists - failed to authorize user, userId {}", userId); - responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value()); - } - if (log.isDebugEnabled()) - log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); - return Either.right(responseFormat); - } - return Either.left(eitherCreator.left().value()); - } - - protected Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) { - Role userRole = Role.valueOf(user.getRole()); - if (roles != null) { - if (!roles.contains(userRole)) { - if (log.isDebugEnabled()) - log.debug("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - return Either.left(Boolean.TRUE); - } - return Either.left(Boolean.FALSE); - } - - protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) { - return lockComponent(component.getUniqueId(), component, ecompErrorContext); - } - - protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); - log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus); - return Either.right(responseFormat); - } - } - - protected void unlockComponent(Either<?, ?> either, Component component, boolean inTransaction) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - if (false == inTransaction) { - if (either == null || either.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - // unlock resource - graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); - } - - protected void unlockComponent(Either<?, ?> either, Component component) { - unlockComponent(either, component, false); - } - - protected <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) { - if (bodyObject == null) { - log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - return Either.left(true); - } - } - - protected Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum == null) { - log.debug("Invalid component type {}", componentType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); - } else { - return Either.left(componentTypeEnum); - } - } - - protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { - - if(filter == null){ - filter = new ComponentParametersView(); - } - Either<Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(componentId, filter); - if (componentFound.isRight()) { - StorageOperationStatus storageOperationStatus = componentFound.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", componentId); - return Either.right(responseFormat); - } - return Either.left(componentFound.left().value()); - } - - public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) { - Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - log.debug("Component {} is not checked-out", component.getName()); - return canWork; - } - - // verify userId is not null - if (userId == null) { - log.debug("Current user userId is null"); - return canWork; - } - - // verify component last update user is the current user - String lastUpdaterUserId = component.getLastUpdaterUserId(); - if (!userId.equals(lastUpdaterUserId)) { - log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); - return canWork; - } - - // verify resource is not deleted - if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) { - log.debug("Component {} is marked as deleted", component.getUniqueId()); - return canWork; - } - - return Either.left(true); - } - - public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { - switch (parentComponentType) { - case SERVICE: - return ComponentTypeEnum.RESOURCE; - case RESOURCE: - return ComponentTypeEnum.RESOURCE; - case PRODUCT: - return ComponentTypeEnum.SERVICE; - default: - break; - } - return null; - } - - // For UT - public void setTitanGenericDao(TitanDao titanDao) { - this.titanDao = titanDao; - } - - protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus operationStatus = allDataTypes.right().value(); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); - } else { - BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - return Either.left(allDataTypes.left().value()); - } - - protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) { - String type = null; - String innerType = null; - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property {} type {}", property.getName(), property.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); - return Either.right(responseFormat); - } - type = property.getType(); - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight().booleanValue()) { - log.info("Invalid inner type for property {} type {}", property.getName(), property.getType() ); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); - return Either.right(responseFormat); - } - } - if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) { - log.info("Invalid default value for property {} type {}", property.getName(), property.getType() ); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); - } - return Either.right(responseFormat); - - } - return Either.left(true); - } - -// protected Either<Resource, StorageOperationStatus> getResource(final String resourceId) { -// -// log.debug("Get resource with id {}", resourceId); -// Either<Resource, StorageOperationStatus> status = resourceOperation.getResource(resourceId); -// if (status.isRight()) { -// log.debug("Resource with id {} was not found", resourceId); -// return Either.right(status.right().value()); -// } -// -// Resource resource = status.left().value(); -// if (resource == null) { -// BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId); -// log.debug("General Error while get resource with id {}", resourceId); -// return Either.right(StorageOperationStatus.GENERAL_ERROR); -// } -// return Either.left(resource); -// } - - protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) { - // convert property - ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType()); - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - - if (newAttributeDef != null) { - SchemaDefinition schema = newAttributeDef.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (schema.getProperty() != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newAttributeDef.getDefaultValue() != null) { - convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes); - newAttributeDef.setDefaultValue(convertedValue); - } - } - } - - protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) { - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - - } - - protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) { - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - } - - protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) { - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - } - - } - - protected ToscaPropertyType getType(String propertyType) { - - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - return type; - - } - - protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) { - if (result == null || result.isRight()) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - - protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); - log.debug("Failed to lock component {} error - {}", name, actionStatus); - return Either.right(responseFormat); - } - } - - protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) { - - Either<Component, StorageOperationStatus> componentFound = null; - componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - - if (componentFound.isRight()) { - StorageOperationStatus storageOperationStatus = componentFound.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", componentId); - return Either.right(responseFormat); - } - return Either.left(componentFound.left().value()); - } - - protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) { - - Either<GroupProperty, ResponseFormat> ret; - final String groupTypeValue = groupPropertyToUpdate.getValue(); - if (!StringUtils.isEmpty(groupTypeValue)) { - if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, - NodeTypeEnum.Property.getName(), - String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH))); - } - - else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, - NodeTypeEnum.Property.getName())); - } else { - ret = Either.left(groupPropertyToUpdate); - } - - } else { - ret = Either.left(groupPropertyToUpdate); - } - return ret; - } - - @SuppressWarnings("unchecked") - protected <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) { - T enumFound = enumGetter.apply(name); - return Arrays.asList(enumValues).contains(enumFound); - } - - protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - innerType = propDef.getType(); - } - - Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); - log.trace("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - return Either.left(newValue); - } - - protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) { - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - innerType = propDef.getType(); - } - - Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); - log.debug("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - return Either.left(newValue); - } - - public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) { - log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); - ToscaPropertyType type = getType(propertyType); - - if (isValidate) { - - if (type == null) { - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); - if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", value, propertyType); - return Either.right(false); - } - JsonElement jsonElement = validateResult.left; - String valueFromJsonElement = getValueFromJsonElement(jsonElement); - return Either.left(valueFromJsonElement); - } - log.trace("before validating property type {}", propertyType); - boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.debug("The value {} of property from type {} is invalid", value, type); - return Either.right(false); - } - } - Object convertedValue = value; - if (false == isEmptyValue(value) && isValidate) { - PropertyValueConverter converter = type.getConverter(); - convertedValue = converter.convert(value, innerType, dataTypes); - } - return Either.left(convertedValue); - } - - public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) { - - if (rules == null || rules.isEmpty() == true) { - return new ImmutablePair<String, Boolean>(null, true); - } - - for (PropertyRule rule : rules) { - String value = rule.getValue(); - Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); - if (updateResult.isRight()) { - Boolean status = updateResult.right().value(); - if (status == false) { - return new ImmutablePair<String, Boolean>(value, status); - } - } else { - String newValue = null; - Object object = updateResult.left().value(); - if (object != null) { - newValue = object.toString(); - } - rule.setValue(newValue); - } - } - - return new ImmutablePair<String, Boolean>(null, true); - } - - protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (isEmptyValue(value)) { - return true; - } - - PropertyTypeValidator validator = type.getValidator(); - - boolean isValid = validator.isValid(value, innerType, dataTypes); - if (true == isValid) { - return true; - } else { - return false; - } - - } - - public boolean isEmptyValue(String value) { - if (value == null) { - return true; - } - return false; - } - - public boolean isNullParam(String value) { - if (value == null) { - return true; - } - return false; - } - - public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { - - List<PropertyRule> rules = resourceInstanceProperty.getRules(); - if (rules == null) { - PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId); - rules = new ArrayList<>(); - rules.add(propertyRule); - } else { - rules = sortRules(rules); - } - - propertyValueData.setRules(rules); - } - - private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { - List<String> path = resourceInstanceProperty.getPath(); - // FOR BC. Since old Property values on VFC/VF does not have rules on - // graph. - // Update could be done on one level only, thus we can use this - // operation to avoid migration. - if (path == null || path.isEmpty() == true) { - path = new ArrayList<>(); - path.add(resourceInstanceId); - } - PropertyRule propertyRule = new PropertyRule(); - propertyRule.setRule(path); - propertyRule.setValue(propertyValueData.getValue()); - return propertyRule; - } - - private List<PropertyRule> sortRules(List<PropertyRule> rules) { - - // TODO: sort the rules by size and binary representation. - // (x, y, .+) --> 110 6 priority 1 - // (x, .+, z) --> 101 5 priority 2 - - return rules; - } - - protected String getValueFromJsonElement(JsonElement jsonElement) { - String value = null; - - if (jsonElement == null || jsonElement.isJsonNull()) { - value = EMPTY_VALUE; - } else { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - - return value; - } + private static final Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class); + + private static final String EMPTY_VALUE = null; + @Autowired + protected ComponentsUtils componentsUtils; + + @Autowired + protected IUserBusinessLogic userAdmin; + + @Autowired + protected IGraphLockOperation graphLockOperation; + + @Autowired + protected TitanDao titanDao; + + @Autowired + protected TitanGenericDao titanGenericDao; + + @Autowired + protected IElementOperation elementDao; + + @Autowired + protected IGroupOperation groupOperation; + + @Autowired + protected IGroupInstanceOperation groupInstanceOperation; + + @Autowired + protected IGroupTypeOperation groupTypeOperation; + + @Autowired + protected GroupBusinessLogic groupBusinessLogic; + + @Autowired + protected PolicyTypeOperation policyTypeOperation; + + @javax.annotation.Resource + protected ArtifactsOperations artifactToscaOperation; + + @Autowired + protected PropertyOperation propertyOperation; + + @Autowired + protected ApplicationDataTypeCache applicationDataTypeCache; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @Autowired + protected ApplicationDataTypeCache dataTypeCache; + + @Autowired + protected ForwardingPathOperation forwardingPathOperation; + + @javax.annotation.Resource + private UserValidations userValidations; + + protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } + + public void setUserValidations(UserValidations userValidations) { + this.userValidations = userValidations; + } + + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { + this.graphLockOperation = graphLockOperation; + } + + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation){ + this.forwardingPathOperation = forwardingPathOperation; + } + + public void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) { + this.policyTypeOperation = policyTypeOperation; + } + + + public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) { + this.dataTypeCache = dataTypeCache; + } + + public void setPropertyOperation(PropertyOperation propertyOperation) { + this.propertyOperation = propertyOperation; + } + + protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) { + return userValidations.validateUserNotEmpty(user, ecompErrorContext); + } + + protected Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { + return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); + } + + protected void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) { + userValidations.validateUserExist(userId, ecompErrorContext, errorWrapper); + } + + public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) { + return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext); + } + + public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { + return userValidations.validateUserExists(userId, ecompErrorContext, inTransaction); + } + + protected Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) { + return userValidations.validateUserRole(user, roles); + } + + protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) { + return lockComponent(component.getUniqueId(), component, ecompErrorContext); + } + + protected Either<Component, ResponseFormat> lockComponent(Component component, boolean shoulLock, String ecompErrorContext) { + return shoulLock ? lockComponent(component.getUniqueId(), component, ecompErrorContext) + .either(l -> Either.left(component), Either::right) : Either.left(component); + } + + protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); + log.debug("Failed to lock component {} error - {}", componentId, actionStatus); + return Either.right(responseFormat); + } + } + + protected void unlockComponent(Either<?, ?> either, Component component, boolean inTransaction) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + if (!inTransaction) { + if (either == null || either.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + // unlock resource + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } + + protected void unlockComponent(Either<?, ?> either, Component component) { + unlockComponent(either, component, false); + } + protected void unlockComponentById(Either<?, ?> either, String componentId) { + Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId); + if(component.isLeft() && component != null) { + unlockComponent(either, component.left().value(), false); + } + } + + protected <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) { + if (bodyObject == null) { + log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + return Either.left(true); + } + } + + protected Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum == null) { + log.debug("Invalid component type {}", componentType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); + } else { + return Either.left(componentTypeEnum); + } + } + + protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { + if (filter == null) { + filter = new ComponentParametersView(); + } + return toscaOperationFacade.getToscaElement(componentId, filter) + .right() + .map(err -> handleGetComponentError(componentId, componentType, err)) + .left() + .bind(cmpt -> validateComponentType(cmpt, componentType)); + } + + private Either<Component, ResponseFormat> validateComponentType(Component cmpt, ComponentTypeEnum componentType) { + if (componentType != cmpt.getComponentType()) { + log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType); + ActionStatus cmptNotFoundError = componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType); + return Either.right(componentsUtils.getResponseFormat(cmptNotFoundError)); + } + return Either.left(cmpt); + } + + protected <T extends PropertyDataDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) { + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + if (allDataTypesEither.isRight()) { + TitanOperationStatus status = allDataTypesEither.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value(); + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + if (!isInput) { + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } + return Either.left(newValue); + } + + public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) { + Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + log.debug("Component {} is not checked-out", component.getName()); + return canWork; + } + + // verify userId is not null + if (userId == null) { + log.debug("Current user userId is null"); + return canWork; + } + + // verify component last update user is the current user + String lastUpdaterUserId = component.getLastUpdaterUserId(); + if (!userId.equals(lastUpdaterUserId)) { + log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); + return canWork; + } + + // verify resource is not deleted + if (Boolean.TRUE.equals(component.getIsDeleted())) { + log.debug("Component {} is marked as deleted", component.getUniqueId()); + return canWork; + } + + return Either.left(true); + } + + public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { + switch (parentComponentType) { + case SERVICE: + return ComponentTypeEnum.RESOURCE; + case RESOURCE: + return ComponentTypeEnum.RESOURCE; + case PRODUCT: + return ComponentTypeEnum.SERVICE; + default: + break; + } + return null; + } + + // For UT + public void setTitanGenericDao(TitanDao titanDao) { + this.titanDao = titanDao; + } + + protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus operationStatus = allDataTypes.right().value(); + if (operationStatus == TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); + } else { + BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + return Either.left(allDataTypes.left().value()); + } + + protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) { + String type = null; + String innerType = null; + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + return Either.right(responseFormat); + } + type = property.getType(); + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight().booleanValue()) { + log.info("Invalid inner type for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + return Either.right(responseFormat); + } + } + if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) { + log.info("Invalid default value for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); + } else { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); + } + return Either.right(responseFormat); + + } + return Either.left(true); + } + + + protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) { + // convert property + ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType()); + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + + if (newAttributeDef != null) { + SchemaDefinition schema = newAttributeDef.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (schema.getProperty() != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newAttributeDef.getDefaultValue() != null) { + convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes); + newAttributeDef.setDefaultValue(convertedValue); + } + } + } + + protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) { + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + + } + + protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) { + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + } + + protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) { + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + } + + protected ToscaPropertyType getType(String propertyType) { + return ToscaPropertyType.isValidType(propertyType); + } + + protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) { + if (result == null || result.isRight()) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + + protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); + log.debug("Failed to lock component {} error - {}", name, actionStatus); + return Either.right(responseFormat); + } + } + + protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { + return toscaOperationFacade.getToscaElement(componentId, componentParametersView) + .right() + .map(err -> handleGetComponentError(componentId, componentType, err)); + + } + + private ResponseFormat handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError); + return responseFormat; + } + + protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) { + + Either<GroupProperty, ResponseFormat> ret; + final String groupTypeValue = groupPropertyToUpdate.getValue(); + if (!StringUtils.isEmpty(groupTypeValue)) { + if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, + NodeTypeEnum.Property.getName(), + String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH))); + } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, + NodeTypeEnum.Property.getName())); + } else { + ret = Either.left(groupPropertyToUpdate); + } + + } else { + ret = Either.left(groupPropertyToUpdate); + } + return ret; + } + + + @SafeVarargs + static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) { + T enumFound = enumGetter.apply(name); + return Arrays.asList(enumValues).contains(enumFound); + } + + Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.trace("After validateAndUpdateRules. pair = {}", pair); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) { + log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); + ToscaPropertyType type = getType(propertyType); + + if (isValidate) { + + if (type == null) { + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + if (Boolean.FALSE.equals(validateResult.right)) { + log.debug("The value {} of property from type {} is invalid", value, propertyType); + return Either.right(false); + } + JsonElement jsonElement = validateResult.left; + String valueFromJsonElement = getValueFromJsonElement(jsonElement); + return Either.left(valueFromJsonElement); + } + log.trace("before validating property type {}", propertyType); + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (!isValidProperty) { + log.debug("The value {} of property from type {} is invalid", value, type); + return Either.right(false); + } + } + Object convertedValue = value; + if (!isEmptyValue(value) && isValidate) { + PropertyValueConverter converter = type.getConverter(); + convertedValue = converter.convert(value, innerType, dataTypes); + } + return Either.left(convertedValue); + } + + public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) { + + if (rules == null || rules.isEmpty()) { + return ImmutablePair.of(null, true); + } + + for (PropertyRule rule : rules) { + String value = rule.getValue(); + Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); + if (updateResult.isRight()) { + Boolean status = updateResult.right().value(); + if (Boolean.FALSE.equals(status)) { + return ImmutablePair.of(value, status); + } + } else { + String newValue = null; + Object object = updateResult.left().value(); + if (object != null) { + newValue = object.toString(); + } + rule.setValue(newValue); + } + } + + return ImmutablePair.of(null, true); + } + + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + return validator.isValid(value, innerType, dataTypes); + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } + + public boolean isNullParam(String value) { + if (value == null) { + return true; + } + return false; + } + + public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + + List<PropertyRule> rules = resourceInstanceProperty.getRules(); + if (rules == null) { + PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId); + rules = new ArrayList<>(); + rules.add(propertyRule); + } else { + rules = sortRules(rules); + } + + propertyValueData.setRules(rules); + } + + private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + List<String> path = resourceInstanceProperty.getPath(); + // FOR BC. Since old Property values on VFC/VF does not have rules on + // graph. + // Update could be done on one level only, thus we can use this + // operation to avoid migration. + if (isEmpty(path)) { + path = new ArrayList<>(); + path.add(resourceInstanceId); + } + PropertyRule propertyRule = new PropertyRule(); + propertyRule.setRule(path); + propertyRule.setValue(propertyValueData.getValue()); + return propertyRule; + } + + private List<PropertyRule> sortRules(List<PropertyRule> rules) { + + // TODO: sort the rules by size and binary representation. + // (x, y, .+) --> 110 6 priority 1 + // (x, .+, z) --> 101 5 priority 2 + + return rules; + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java index 5cf42cedd6..caf051ec81 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import javax.annotation.Resource; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -41,83 +34,87 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; @Component("capabilityTypeImportManager") public class CapabilityTypeImportManager { - private static Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class.getName()); - @Resource - private CapabilityTypeOperation capabilityTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - public Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes(String capabilityYml) { - Either<List<CapabilityTypeDefinition>, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml); - if (capabilityTypes.isRight()) { - ActionStatus status = capabilityTypes.right().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null); - return Either.right(responseFormat); - } - return createCapabilityTypesByDao(capabilityTypes.left().value()); - - } - - private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) { - return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData)); - - } - - private Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) { - List<CapabilityTypeDefinition> createdCapabilities = new ArrayList<>(); - Either<List<CapabilityTypeDefinition>, ResponseFormat> eitherResult = Either.left(createdCapabilities); - Iterator<CapabilityTypeDefinition> capTypeItr = capabilityTypesToCreate.iterator(); - boolean stopDao = false; - while (capTypeItr.hasNext() && !stopDao) { - CapabilityTypeDefinition capabilityType = capTypeItr.next(); - - log.info("send capabilityType {} to dao for create", capabilityType.getType()); - Either<CapabilityTypeDefinition, StorageOperationStatus> dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType); - if (dataModelResponse.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingCapabilityTypeError, "Create CapabilityTypes"); - BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type"); - log.debug("failed to create capabilityType: {}", capabilityType.getType()); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType); - eitherResult = Either.right(responseFormat); - stopDao = true; - } - - } else { - createdCapabilities.add(capabilityType); - } - if (!capTypeItr.hasNext()) { - log.info("capabilityTypes were created successfully!!!"); - } - - } - - return eitherResult; - - } - - private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) { - CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); - - capabilityType.setType(capabilityTypeName); - - // Description - final Consumer<String> descriptionSetter = description -> capabilityType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer<String> derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values)); - - return capabilityType; - } + private static final Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class); + @Resource + private CapabilityTypeOperation capabilityTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + public Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes(String capabilityYml) { + Either<List<CapabilityTypeDefinition>, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml); + if (capabilityTypes.isRight()) { + ActionStatus status = capabilityTypes.right().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null); + return Either.right(responseFormat); + } + return createCapabilityTypesByDao(capabilityTypes.left().value()); + + } + + private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) { + return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData)); + + } + + private Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) { + List<CapabilityTypeDefinition> createdCapabilities = new ArrayList<>(); + Either<List<CapabilityTypeDefinition>, ResponseFormat> eitherResult = Either.left(createdCapabilities); + Iterator<CapabilityTypeDefinition> capTypeItr = capabilityTypesToCreate.iterator(); + boolean stopDao = false; + while (capTypeItr.hasNext() && !stopDao) { + CapabilityTypeDefinition capabilityType = capTypeItr.next(); + + log.info("send capabilityType {} to dao for create", capabilityType.getType()); + Either<CapabilityTypeDefinition, StorageOperationStatus> dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType); + if (dataModelResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type"); + log.debug("failed to create capabilityType: {}", capabilityType.getType()); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType); + eitherResult = Either.right(responseFormat); + stopDao = true; + } + + } else { + createdCapabilities.add(capabilityType); + } + if (!capTypeItr.hasNext()) { + log.info("capabilityTypes were created successfully!!!"); + } + + } + + return eitherResult; + + } + + private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) { + CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); + + capabilityType.setType(capabilityTypeName); + + // Description + final Consumer<String> descriptionSetter = description -> capabilityType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer<String> derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values)); + + return capabilityType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java index 1f5770856b..31db9651c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java @@ -1,5 +1,18 @@ package org.openecomp.sdc.be.components.impl; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.Session; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils; +import org.openecomp.sdc.be.dao.cassandra.schema.Table; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; @@ -10,178 +23,163 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import javax.annotation.PostConstruct; +@Component("cassandra-health-check") +public class CassandraHealthCheck { -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils; -import org.openecomp.sdc.be.dao.cassandra.schema.Table; -import org.openecomp.sdc.common.util.GeneralUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.Metadata; -import com.datastax.driver.core.Session; + private static final Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class); -@Component("cassandra-health-check") -public class CassandraHealthCheck { - - - private static Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class.getName()); - - private String localDataCenterName = null; - - private Set<String> sdcKeyspaces = new HashSet<String>(); - - private int HC_FormulaNumber; - - @PostConstruct - private void init() { - - //Initialize local data center name - this field must be filled by DevOps - localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter(); - - if (GeneralUtility.isEmptyString(localDataCenterName)) { - log.error("localDataCenter Name in configuration.yaml is missing."); - return; - } - - //Collect all SDC keyspaces - for (Table table : Table.values()) { - sdcKeyspaces.add(table.getTableDescription().getKeyspace()); - } - - String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); - Properties prop = new Properties(); - InputStream titanProp = null; - try { - //load a properties file - titanProp = new FileInputStream(titanCfgFile); - prop.load(titanProp); - //Add titan keyspace - String titanKeyspace = prop.getProperty("storage.cassandra.keyspace"); - if (!GeneralUtility.isEmptyString(titanKeyspace)) { - sdcKeyspaces.add(titanKeyspace); - } - } catch (Exception e) { - log.error("Failed to open titen.properties file , url is : {}", titanCfgFile); - } - - log.info("All sdc keyspaces are : {}", sdcKeyspaces); - - //Calculate the Formula of Health Check - Cluster cluster = null; - try { - - log.info("creating cluster for Cassandra Health Check."); - //Create cluster from nodes in cassandra configuration - cluster = SdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); - return; - } - - Metadata metadata = cluster.getMetadata(); - - if (metadata == null) { - log.error("Failure get cassandra metadata."); - return; - } - - log.info("Cluster Metadata: {}", metadata.toString()); - List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); - List<Integer> replactionFactorList = new ArrayList<Integer>(); - - //Collect the keyspaces Replication Factor of current localDataCenter - for (KeyspaceMetadata keyspace : keyspaces) { - - if (sdcKeyspaces.contains(keyspace.getName())) { - - log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication()); - Map<String, String> replicationOptions = keyspace.getReplication(); - - //In 1 site with one data center - if (replicationOptions.containsKey("replication_factor")) { - replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor"))); - } - //In multiple sites with some data center - else if (replicationOptions.containsKey(localDataCenterName)) { - replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName))); - } - } - } - - if (replactionFactorList.size() == 0) { - log.error("Replication factor NOT found in all keyspaces"); - return; - } - - int maxReplicationFactor = Collections.max(replactionFactorList); - log.info("maxReplication Factor is: {}", maxReplicationFactor); - - int localQuorum = maxReplicationFactor/2 + 1; - log.info("localQuorum is: {}", localQuorum); - - HC_FormulaNumber = maxReplicationFactor - localQuorum; - - log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber); - - - } catch (Exception e) { - log.error("create cassandra cluster failed with exception.", e); - } finally { - if (cluster != null) { - cluster.close(); - } - } - - } - - public boolean getCassandraStatus() { - - if (GeneralUtility.isEmptyString(localDataCenterName)) { - log.error("localDataCenter Name in configuration.yaml is missing."); - return false; - } - - Cluster cluster = null; - Session session = null; - try { - log.info("creating cluster for Cassandra for monitoring."); - cluster = SdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); - return false; - } - session = cluster.connect(); - Metadata metadata = cluster.getMetadata(); - - if (metadata == null) { - log.error("Failure get cassandra metadata."); - return false; - } - - log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size()); - - //Count the number of data center nodes that are down - Long downHostsNumber = metadata.getAllHosts().stream() - .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count(); - - log.info("The cassandra down nodes number is {}", downHostsNumber.toString()); - return (HC_FormulaNumber >= downHostsNumber); - - } catch (Exception e) { - log.error("create cassandra cluster failed with exception.", e); - return false; - } finally { - if (session != null) { + private String localDataCenterName = null; + + private Set<String> sdcKeyspaces = new HashSet<String>(); + + private int HC_FormulaNumber; + + @PostConstruct + private void init() { + + //Initialize local data center name - this field must be filled by DevOps + localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter(); + + if (GeneralUtility.isEmptyString(localDataCenterName)) { + log.error("localDataCenter Name in configuration.yaml is missing."); + return; + } + + //Collect all SDC keyspaces + for (Table table : Table.values()) { + sdcKeyspaces.add(table.getTableDescription().getKeyspace()); + } + + String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); + Properties prop = new Properties(); + InputStream titanProp = null; + try { + //load a properties file + titanProp = new FileInputStream(titanCfgFile); + prop.load(titanProp); + //Add titan keyspace + String titanKeyspace = prop.getProperty("storage.cassandra.keyspace"); + if (!GeneralUtility.isEmptyString(titanKeyspace)) { + sdcKeyspaces.add(titanKeyspace); + } + } catch (Exception e) { + log.error("Failed to open titen.properties file , url is : {}", titanCfgFile, e); + } + + log.info("All sdc keyspaces are : {}", sdcKeyspaces); + + //Calculate the Formula of Health Check + Cluster cluster = null; + try { + + log.info("creating cluster for Cassandra Health Check."); + //Create cluster from nodes in cassandra configuration + cluster = SdcSchemaUtils.createCluster(); + if (cluster == null) { + log.error("Failure create cassandra cluster."); + return; + } + + Metadata metadata = cluster.getMetadata(); + + if (metadata == null) { + log.error("Failure get cassandra metadata."); + return; + } + + log.info("Cluster Metadata: {}", metadata); + List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); + List<Integer> replactionFactorList = new ArrayList<Integer>(); + + //Collect the keyspaces Replication Factor of current localDataCenter + for (KeyspaceMetadata keyspace : keyspaces) { + + if (sdcKeyspaces.contains(keyspace.getName())) { + + log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication()); + Map<String, String> replicationOptions = keyspace.getReplication(); + + //In 1 site with one data center + if (replicationOptions.containsKey("replication_factor")) { + replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor"))); + } + //In multiple sites with some data center + else if (replicationOptions.containsKey(localDataCenterName)) { + replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName))); + } + } + } + + if (replactionFactorList.size() == 0) { + log.error("Replication factor NOT found in all keyspaces"); + return; + } + + int maxReplicationFactor = Collections.max(replactionFactorList); + log.info("maxReplication Factor is: {}", maxReplicationFactor); + + int localQuorum = maxReplicationFactor/2 + 1; + log.info("localQuorum is: {}", localQuorum); + + HC_FormulaNumber = maxReplicationFactor - localQuorum; + + log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber); + + + } catch (Exception e) { + log.error("create cassandra cluster failed with exception.", e); + } finally { + if (cluster != null) { + cluster.close(); + } + } + + } + + public boolean getCassandraStatus() { + + if (GeneralUtility.isEmptyString(localDataCenterName)) { + log.error("localDataCenter Name in configuration.yaml is missing."); + return false; + } + + Cluster cluster = null; + Session session = null; + try { + log.info("creating cluster for Cassandra for monitoring."); + cluster = SdcSchemaUtils.createCluster(); + if (cluster == null) { + log.error("Failure create cassandra cluster."); + return false; + } + session = cluster.connect(); + Metadata metadata = cluster.getMetadata(); + + if (metadata == null) { + log.error("Failure get cassandra metadata."); + return false; + } + + log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size()); + + //Count the number of data center nodes that are down + Long downHostsNumber = metadata.getAllHosts().stream() + .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count(); + + log.info("The cassandra down nodes number is {}", downHostsNumber); + return HC_FormulaNumber >= downHostsNumber; + + } catch (Exception e) { + log.error("create cassandra cluster failed with exception.", e); + return false; + } finally { + if (session != null) { session.close(); } - if (cluster != null) { - cluster.close(); - } - } - } + if (cluster != null) { + cluster.close(); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java index 57ab46346a..fa662898d8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; @@ -45,230 +39,229 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; @Component("categoriesImportManager") public class CategoriesImportManager { - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private IElementOperation elementOperation; - private static Logger log = LoggerFactory.getLogger(CategoriesImportManager.class.getName()); + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) { + private static final Logger log = LoggerFactory.getLogger(CategoriesImportManager.class); - Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml); - return createCategoriesByDao(allCategories); - } + public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) { - private Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategoriesByDao(Map<String, List<CategoryDefinition>> allCategories) { - Map<String, List<CategoryDefinition>> result = new HashMap<>(); - log.debug("createCategoriesByDao: starting to create Categories."); - for (Map.Entry<String, List<CategoryDefinition>> entry : allCategories.entrySet()) { - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey()); - NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY); - NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY); - NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING); - log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); - List<CategoryDefinition> newCategoriesvalue = new ArrayList<>(); - for (CategoryDefinition category : entry.getValue()) { + Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml); + return createCategoriesByDao(allCategories); + } - Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory); - if (createdCategoryRes.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } + private Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategoriesByDao(Map<String, List<CategoryDefinition>> allCategories) { + Map<String, List<CategoryDefinition>> result = new HashMap<>(); + log.debug("createCategoriesByDao: starting to create Categories."); + for (Map.Entry<String, List<CategoryDefinition>> entry : allCategories.entrySet()) { + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey()); + NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY); + NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY); + NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING); + log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); + List<CategoryDefinition> newCategoriesvalue = new ArrayList<>(); + for (CategoryDefinition category : entry.getValue()) { - CategoryDefinition newcategory = createdCategoryRes.left().value(); - String categoryId = newcategory.getUniqueId(); - log.debug("createCategoriesByDao: create category was successful {}", newcategory); - List<SubCategoryDefinition> newsubcategories = new ArrayList<>(); - List<SubCategoryDefinition> subcategories = category.getSubcategories(); - if (subcategories != null) { - for (SubCategoryDefinition subcategory : subcategories) { - Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); - if (createdSubCategory.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); - List<GroupingDefinition> groupings = subcategory.getGroupings(); - if (groupings != null) { - List<GroupingDefinition> newgroupings = new ArrayList<>(); - for (GroupingDefinition grouping : groupings) { - Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); - if (createdGrouping.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - newgroupings.add(createdGrouping.left().value()); - } - newsubcategory.setGroupings(newgroupings); - } - newsubcategories.add(newsubcategory); - } - newcategory.setSubcategories(newsubcategories); - } - newCategoriesvalue.add(newcategory); - } - result.put(entry.getKey(), newCategoriesvalue); - } - return Either.left(result); - } + Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory); + if (createdCategoryRes.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } - private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { + CategoryDefinition newcategory = createdCategoryRes.left().value(); + log.debug("createCategoriesByDao: create category was successful {}", newcategory); + List<SubCategoryDefinition> newsubcategories = new ArrayList<>(); + List<SubCategoryDefinition> subcategories = category.getSubcategories(); + if (subcategories != null) { + for (SubCategoryDefinition subcategory : subcategories) { + Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); + if (createdSubCategory.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } + SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); + List<GroupingDefinition> groupings = subcategory.getGroupings(); + if (groupings != null) { + List<GroupingDefinition> newgroupings = new ArrayList<>(); + for (GroupingDefinition grouping : groupings) { + Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); + if (createdGrouping.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } + newgroupings.add(createdGrouping.left().value()); + } + newsubcategory.setGroupings(newgroupings); + } + newsubcategories.add(newsubcategory); + } + newcategory.setSubcategories(newsubcategories); + } + newCategoriesvalue.add(newcategory); + } + result.put(entry.getKey(), newCategoriesvalue); + } + return Either.left(result); + } - log.debug("createGroupingDeo: creating grouping {}", grouping); - Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); - if (createdGrouping.isRight()) { - if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { - log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); - String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); - createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); - if (createdGrouping.isRight()) { - log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup); - return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); - } - } - log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), - category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null, - createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null); - - return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); - } else { - log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value()); - } - return Either.left(createdGrouping.left().value()); + private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { - } + log.debug("createGroupingDeo: creating grouping {}", grouping); + Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); + if (createdGrouping.isRight()) { + if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { + log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); + String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); + createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); + if (createdGrouping.isRight()) { + log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup); + return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); + } + } + log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), + category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null, + createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null); - private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) { - log.debug("createSubCategorieDeo: creating subcategory {}", subcategory); - Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); - if (createdSubCategory.isRight()) { - if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { - log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); - String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); - createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); - if (createdSubCategory.isRight()) { - log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory); - return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); - } - } else { - log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); - return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); - } - } else { - log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value()); - } - return Either.left(createdSubCategory.left().value()); - } + return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); + } else { + log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value()); + } + return Either.left(createdGrouping.left().value()); - private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) { - log.debug("createCategorieDeo: creating category {}", category); - Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory); - if (createdCategory.isRight()) { - log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); - if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { - return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); - } else { - log.debug("createCategorieDeo: category exists {} retriving.", category); - String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory); - createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId); - if (createdCategory.isRight()) { - log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory); - return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); - } - } - } else { - log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value()); - } - return Either.left(createdCategory.left().value()); - } + } - private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) { - Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml); - Map<String, List<CategoryDefinition>> allCategories = new HashMap<>(); + private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) { + log.debug("createSubCategorieDeo: creating subcategory {}", subcategory); + Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); + if (createdSubCategory.isRight()) { + if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { + log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); + String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); + createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); + if (createdSubCategory.isRight()) { + log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory); + return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); + } + } else { + log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); + return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); + } + } else { + log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value()); + } + return Either.left(createdSubCategory.left().value()); + } - Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator(); - while (categoryEntryItr.hasNext()) { - Entry<String, Object> categoryTypeEntry = categoryEntryItr.next(); - String categoryType = categoryTypeEntry.getKey(); - List<CategoryDefinition> categoriesPerType = null; - Map<String, Object> categoryPerType = null; - switch (categoryType) { - case ComponentTypeEnum.SERVICE_PARAM_NAME: - categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue(); - categoriesPerType = createServiceCategories(categoryPerType); - break; - case ComponentTypeEnum.RESOURCE_PARAM_NAME: - categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue(); - categoriesPerType = createResourceCategories(categoryPerType); - break; - case ComponentTypeEnum.PRODUCT_PARAM_NAME: - // TODO - break; - default: - log.debug("Not supported category type - {}", categoryType); - break; - } - if (categoriesPerType != null) { - allCategories.put(categoryType, categoriesPerType); - } - } - return allCategories; - } + private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) { + log.debug("createCategorieDeo: creating category {}", category); + Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory); + if (createdCategory.isRight()) { + log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); + if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { + return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); + } else { + log.debug("createCategorieDeo: category exists {} retriving.", category); + String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory); + createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId); + if (createdCategory.isRight()) { + log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory); + return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); + } + } + } else { + log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value()); + } + return Either.left(createdCategory.left().value()); + } - private List<CategoryDefinition> createServiceCategories(Map<String, Object> categories) { - List<CategoryDefinition> categroiesDef = new ArrayList<>(); - String catName = null; - List<String> icons = null; - for (Entry<String, Object> entry : categories.entrySet()) { - CategoryDefinition catDef = new CategoryDefinition(); - Map<String, Object> category = (Map<String, Object>) entry.getValue(); - catName = (String) category.get("name"); - catDef.setName(catName); - icons = (List<String>) category.get("icons"); - catDef.setIcons(icons); - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); - catDef.setNormalizedName(normalizedName); - categroiesDef.add(catDef); - } + private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) { + Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml); + Map<String, List<CategoryDefinition>> allCategories = new HashMap<>(); - return categroiesDef; - } + Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator(); + while (categoryEntryItr.hasNext()) { + Entry<String, Object> categoryTypeEntry = categoryEntryItr.next(); + String categoryType = categoryTypeEntry.getKey(); + List<CategoryDefinition> categoriesPerType = null; + Map<String, Object> categoryPerType = null; + switch (categoryType) { + case ComponentTypeEnum.SERVICE_PARAM_NAME: + categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue(); + categoriesPerType = createServiceCategories(categoryPerType); + break; + case ComponentTypeEnum.RESOURCE_PARAM_NAME: + categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue(); + categoriesPerType = createResourceCategories(categoryPerType); + break; + case ComponentTypeEnum.PRODUCT_PARAM_NAME: + // TODO + break; + default: + log.debug("Not supported category type - {}", categoryType); + break; + } + if (categoriesPerType != null) { + allCategories.put(categoryType, categoriesPerType); + } + } + return allCategories; + } - private List<CategoryDefinition> createResourceCategories(Map<String, Object> categoryPerType) { - List<CategoryDefinition> categroiesDef = new ArrayList<>(); - for (Map.Entry<String, Object> entry : categoryPerType.entrySet()) { - Map<String, Object> category = (Map<String, Object>) entry.getValue(); - CategoryDefinition catDef = new CategoryDefinition(); - String catName = (String) category.get("name"); - catDef.setName(catName); - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); - catDef.setNormalizedName(normalizedName); - Map<String, Object> subcategories = (Map<String, Object>) category.get("subcategories"); - List<SubCategoryDefinition> subcateDef = new ArrayList<>(); - for (Entry<String, Object> subcategory : subcategories.entrySet()) { - Map<String, Object> subcategoryInfo = (Map<String, Object>) subcategory.getValue(); - SubCategoryDefinition subDef = new SubCategoryDefinition(); - String subcategoryName = (String) subcategoryInfo.get("name"); - subDef.setName(subcategoryName); - List<String> subcategoryIcons = (List<String>) subcategoryInfo.get("icons"); - subDef.setIcons(subcategoryIcons); - normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName); - subDef.setNormalizedName(normalizedName); - subcateDef.add(subDef); - } + private List<CategoryDefinition> createServiceCategories(Map<String, Object> categories) { + List<CategoryDefinition> categroiesDef = new ArrayList<>(); + String catName = null; + List<String> icons = null; + for (Entry<String, Object> entry : categories.entrySet()) { + CategoryDefinition catDef = new CategoryDefinition(); + Map<String, Object> category = (Map<String, Object>) entry.getValue(); + catName = (String) category.get("name"); + catDef.setName(catName); + icons = (List<String>) category.get("icons"); + catDef.setIcons(icons); + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); + catDef.setNormalizedName(normalizedName); + categroiesDef.add(catDef); + } - catDef.setSubcategories(subcateDef); - categroiesDef.add(catDef); - } - return categroiesDef; - } + return categroiesDef; + } - public static void setLog(Logger log) { - CategoriesImportManager.log = log; - } + private List<CategoryDefinition> createResourceCategories(Map<String, Object> categoryPerType) { + List<CategoryDefinition> categroiesDef = new ArrayList<>(); + for (Map.Entry<String, Object> entry : categoryPerType.entrySet()) { + Map<String, Object> category = (Map<String, Object>) entry.getValue(); + CategoryDefinition catDef = new CategoryDefinition(); + String catName = (String) category.get("name"); + catDef.setName(catName); + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); + catDef.setNormalizedName(normalizedName); + Map<String, Object> subcategories = (Map<String, Object>) category.get("subcategories"); + List<SubCategoryDefinition> subcateDef = new ArrayList<>(); + for (Entry<String, Object> subcategory : subcategories.entrySet()) { + Map<String, Object> subcategoryInfo = (Map<String, Object>) subcategory.getValue(); + SubCategoryDefinition subDef = new SubCategoryDefinition(); + String subcategoryName = (String) subcategoryInfo.get("name"); + subDef.setName(subcategoryName); + List<String> subcategoryIcons = (List<String>) subcategoryInfo.get("icons"); + subDef.setIcons(subcategoryIcons); + normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName); + subDef.setNormalizedName(normalizedName); + subcateDef.add(subDef); + } + catDef.setSubcategories(subcateDef); + categroiesDef.add(catDef); + } + return categroiesDef; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java index 31c665686e..055e479d0d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java @@ -20,27 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.PolicyTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.exception.ResponseFormat; @@ -49,260 +35,279 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; -import jersey.repackaged.com.google.common.base.Function; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; @Component("commonImportManager") public class CommonImportManager { - private static Logger log = LoggerFactory.getLogger(CommonImportManager.class.getName()); - - @Resource - private ComponentsUtils componentsUtils; - @Resource - private PropertyOperation propertyOperation; - - protected void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) { - consumer.accept(getProperties(toscaJson)); - } - - private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) { - List<PropertyDefinition> values = null; - Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson); - - if (properties.isLeft()) { - values = new ArrayList<>(); - Map<String, PropertyDefinition> propertiesMap = properties.left().value(); - if (propertiesMap != null && propertiesMap.isEmpty() == false) { - - for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) { - String propName = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition); - newPropertyDefinition.setName(propName); - values.add(newPropertyDefinition); - } - } - } - - return values; - } - - protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) { - final List<PropertyDefinition> properties = getProperties(toscaJson); - if (properties != null) { - Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); - consumer.accept(collect); - } - - } - - interface ICreateElementType<T1, T2, ElementType> { - ElementType createElement(T1 firstArg, T2 secondArg); - } - - protected <ElementDefinition> Either<List<ElementDefinition>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi) { - - List<ElementDefinition> elementTypes = new ArrayList<>(); - try { - Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml); - - Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator(); - while (elementTypesEntryItr.hasNext()) { - Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next(); - String elementTypeName = elementTypeNameDataEntry.getKey(); - Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue(); - ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData); - elementTypes.add(elementDefinition); - - } - - } catch (Exception e) { - log.debug("Failed to yaml file {}", elementTypesYml, e); - return Either.right(ActionStatus.INVALID_YAML_FILE); - } - return Either.left(elementTypes); - } - - protected <FieldType> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<FieldType> setter) { - if (toscaJson.containsKey(fieldName)) { - FieldType fieldValue = (FieldType) toscaJson.get(fieldName); - setter.accept(fieldValue); - } - - } - - public enum ElementTypeEnum { - PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType - }; - - private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) { - ActionStatus ret; - switch (elementTypeEnum) { - case GroupType: - ret = componentsUtils.convertFromStorageResponseForGroupType(status); - break; - case DataType: - ret = componentsUtils.convertFromStorageResponseForDataType(status); - break; - case CapabilityType: - ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); - break; - case InterfaceLifecycleType: - ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); - break; - default: - ret = componentsUtils.convertFromStorageResponse(status); - break; - } - return ret; - } - - private <ElementTypeDefinition> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) { - ResponseFormat ret; - switch (elementTypeEnum) { - case GroupType: - ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); - break; - case PolicyType: - ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); - break; - case DataType: - ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); - break; - case CapabilityType: - ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); - break; - - default: - ret = componentsUtils.getResponseFormat(actionStatus); - break; - } - return ret; - } - - protected <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypesByDao(List<ElementTypeDefinition> elementTypesToCreate, - Function<ElementTypeDefinition, Either<ActionStatus, ResponseFormat>> validator, Function<ElementTypeDefinition, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter, - Function<String, Either<ElementTypeDefinition, StorageOperationStatus>> elementFetcher, Function<ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementAdder, - BiFunction<ElementTypeDefinition, ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementUpgrader) { - - List<ImmutablePair<ElementTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>(); - - Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes); - - Iterator<ElementTypeDefinition> elementTypeItr = elementTypesToCreate.iterator(); - - try { - - while (elementTypeItr.hasNext()) { - ElementTypeDefinition elementType = elementTypeItr.next(); - final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType); - ElementTypeEnum elementTypeEnum = elementInfo.left; - String elementName = elementInfo.right; - - Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType); - if (validateElementType.isRight()) { - ResponseFormat responseFormat = validateElementType.right().value(); - log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage()); - eitherResult = Either.right(responseFormat); - break; - } - - log.info("send {} : {} to dao for create", elementTypeEnum.name(), elementName); - - Either<ElementTypeDefinition, StorageOperationStatus> findElementType = elementFetcher.apply(elementName); - if (findElementType.isRight()) { - StorageOperationStatus status = findElementType.right().value(); - log.debug("searched {} finished with result:{}", elementTypeEnum.name(), status.name()); - if (status != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType); - eitherResult = Either.right(responseFormat); - break; - } else { - Either<ElementTypeDefinition, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType); - - if (dataModelResponse.isRight()) { - try { - BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name()); - log.debug("failed to create {}: {}", elementTypeEnum.name(), elementName); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); - - eitherResult = Either.right(responseFormat); - break; - } else { - createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); - } - } finally { - propertyOperation.getTitanGenericDao().rollback(); - } - } else { - propertyOperation.getTitanGenericDao().commit(); - createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true)); - log.debug("{} : {} was created successfully.", elementTypeEnum.name(), elementName); - } - if (!elementTypeItr.hasNext()) { - log.info("all {} were created successfully!!!", elementTypeEnum.name()); - } - - } - } else { - - if (elementUpgrader != null) { - Either<ElementTypeDefinition, StorageOperationStatus> upgradeResponse = null; - try { - upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value()); - if (upgradeResponse.isRight()) { - StorageOperationStatus status = upgradeResponse.right().value(); - if (status == StorageOperationStatus.OK) { - createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); - } else { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); - eitherResult = Either.right(responseFormat); - break; - } - } else { - log.debug("{} : {} was upgraded successfully.", elementTypeEnum.name(), elementName); - createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true)); - } - } finally { - if (upgradeResponse == null || upgradeResponse.isRight()) { - propertyOperation.getTitanGenericDao().rollback(); - } else { - propertyOperation.getTitanGenericDao().commit(); - } - } - - } else { - // mshitrit Once GroupType Versions are supported add - // code here - createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); - log.debug("{} : {} already exists.", elementTypeEnum.name(), elementName); - } - - } - - } - } finally { - if (eitherResult.isRight()) { - propertyOperation.getTitanGenericDao().rollback(); - } - } - - return eitherResult; - - } - - public <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<ElementTypeDefinition>, ActionStatus>> elementTypeFromYmlCreater, - Function<List<ElementTypeDefinition>, Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) { - - Either<List<ElementTypeDefinition>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml); - if (elementTypes.isRight()) { - ActionStatus status = elementTypes.right().value(); - ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null); - return Either.right(responseFormat); - } - return elementTypeDaoCreater.apply(elementTypes.left().value()); - - } + private static final Logger log = LoggerFactory.getLogger(CommonImportManager.class); + + @Resource + private ComponentsUtils componentsUtils; + @Resource + private PropertyOperation propertyOperation; + + protected void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) { + consumer.accept(getProperties(toscaJson)); + } + + private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) { + List<PropertyDefinition> values = null; + Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson); + + if (properties.isLeft()) { + values = new ArrayList<>(); + Map<String, PropertyDefinition> propertiesMap = properties.left().value(); + if (propertiesMap != null && propertiesMap.isEmpty() == false) { + + for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) { + String propName = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition); + newPropertyDefinition.setName(propName); + values.add(newPropertyDefinition); + } + } + } + + return values; + } + + protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) { + final List<PropertyDefinition> properties = getProperties(toscaJson); + if (properties != null) { + Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); + consumer.accept(collect); + } + + } + + interface ICreateElementType<T1, T2, ElementType> { + ElementType createElement(T1 firstArg, T2 secondArg); + } + + protected <ElementDefinition> Either<List<ElementDefinition>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi) { + + List<ElementDefinition> elementTypes = new ArrayList<>(); + try { + Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml); + + elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson); + } catch (Exception e) { + log.debug("Failed to yaml file {}", elementTypesYml, e); + return Either.right(ActionStatus.INVALID_YAML_FILE); + } + return Either.left(elementTypes); + } + + /** + * @param createApi * @param createApi + * @param elementTypes + * @param toscaJson + */ + protected <ElementDefinition> List<ElementDefinition> createElementTypesFromToscaJsonMap( + ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi, Map<String, Object> toscaJson) { + List<ElementDefinition> elementTypes = new ArrayList<>(); + + Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator(); + while (elementTypesEntryItr.hasNext()) { + Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next(); + String elementTypeName = elementTypeNameDataEntry.getKey(); + Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue(); + ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData); + elementTypes.add(elementDefinition); + } + return elementTypes; + } + + protected <FieldType> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<FieldType> setter) { + if (toscaJson.containsKey(fieldName)) { + FieldType fieldValue = (FieldType) toscaJson.get(fieldName); + setter.accept(fieldValue); + } + + } + + public enum ElementTypeEnum { + PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType + }; + + private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) { + ActionStatus ret; + switch (elementTypeEnum) { + case GroupType: + ret = componentsUtils.convertFromStorageResponseForGroupType(status); + break; + case DataType: + ret = componentsUtils.convertFromStorageResponseForDataType(status); + break; + case CapabilityType: + ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); + break; + case InterfaceLifecycleType: + ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); + break; + default: + ret = componentsUtils.convertFromStorageResponse(status); + break; + } + return ret; + } + + private <ElementTypeDefinition> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) { + ResponseFormat ret; + switch (elementTypeEnum) { + case GroupType: + ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); + break; + case PolicyType: + ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); + break; + case DataType: + ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); + break; + case CapabilityType: + ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); + break; + + default: + ret = componentsUtils.getResponseFormat(actionStatus); + break; + } + return ret; + } + + protected <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypesByDao(List<ElementTypeDefinition> elementTypesToCreate, + Function<ElementTypeDefinition, Either<ActionStatus, ResponseFormat>> validator, Function<ElementTypeDefinition, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter, + Function<String, Either<ElementTypeDefinition, StorageOperationStatus>> elementFetcher, Function<ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementAdder, + BiFunction<ElementTypeDefinition, ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementUpgrader) { + + List<ImmutablePair<ElementTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>(); + + Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes); + + Iterator<ElementTypeDefinition> elementTypeItr = elementTypesToCreate.iterator(); + + try { + + while (elementTypeItr.hasNext()) { + ElementTypeDefinition elementType = elementTypeItr.next(); + final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType); + ElementTypeEnum elementTypeEnum = elementInfo.left; + String elementName = elementInfo.right; + + Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType); + if (validateElementType.isRight()) { + ResponseFormat responseFormat = validateElementType.right().value(); + log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage()); + eitherResult = Either.right(responseFormat); + break; + } + + log.info("send {} : {} to dao for create", elementTypeEnum, elementName); + + Either<ElementTypeDefinition, StorageOperationStatus> findElementType = elementFetcher.apply(elementName); + if (findElementType.isRight()) { + StorageOperationStatus status = findElementType.right().value(); + log.debug("searched {} finished with result:{}", elementTypeEnum, status.name()); + if (status != StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType); + eitherResult = Either.right(responseFormat); + break; + } else { + Either<ElementTypeDefinition, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType); + + if (dataModelResponse.isRight()) { + try { + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name()); + log.debug("failed to create {}: {}", elementTypeEnum, elementName); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + + eitherResult = Either.right(responseFormat); + break; + } else { + createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); + } + } finally { + propertyOperation.getTitanGenericDao().rollback(); + } + } else { + propertyOperation.getTitanGenericDao().commit(); + createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true)); + log.debug("{} : {} was created successfully.", elementTypeEnum, elementName); + } + if (!elementTypeItr.hasNext()) { + log.info("all {} were created successfully!!!", elementTypeEnum); + } + + } + } else { + + if (elementUpgrader != null) { + Either<ElementTypeDefinition, StorageOperationStatus> upgradeResponse = null; + try { + upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value()); + if (upgradeResponse.isRight()) { + StorageOperationStatus status = upgradeResponse.right().value(); + if (status == StorageOperationStatus.OK) { + createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); + } else { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + eitherResult = Either.right(responseFormat); + break; + } + } else { + log.debug("{} : {} was upgraded successfully.", elementTypeEnum, elementName); + createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true)); + } + } finally { + if (upgradeResponse == null || upgradeResponse.isRight()) { + propertyOperation.getTitanGenericDao().rollback(); + } else { + propertyOperation.getTitanGenericDao().commit(); + } + } + + } else { + // mshitrit Once GroupType Versions are supported add + // code here + createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false)); + log.debug("{} : {} already exists.", elementTypeEnum, elementName); + } + + } + + } + } finally { + if (eitherResult.isRight()) { + propertyOperation.getTitanGenericDao().rollback(); + } + } + + return eitherResult; + + } + + public <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<ElementTypeDefinition>, ActionStatus>> elementTypeFromYmlCreater, + Function<List<ElementTypeDefinition>, Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) { + + Either<List<ElementTypeDefinition>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml); + if (elementTypes.isRight()) { + ActionStatus status = elementTypes.right().value(); + ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null); + return Either.right(responseFormat); + } + return elementTypeDaoCreater.apply(elementTypes.left().value()); + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index 40e67aa876..4688aa4b8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -42,31 +35,17 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapReqDef; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.utils.CommonBeUtils; @@ -79,1070 +58,1077 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; public abstract class ComponentBusinessLogic extends BaseBusinessLogic { - @Autowired - protected ArtifactsBusinessLogic artifactsBusinessLogic; - - @Autowired - protected ComponentCache componentCache; - - @Autowired - private GenericTypeBusinessLogic genericTypeBusinessLogic; - - public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { - this.genericTypeBusinessLogic = genericTypeBusinessLogic; - } - - private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName()); - - private static final String TAG_FIELD_LABEL = "tag"; - - public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents(); - - public abstract ComponentInstanceBusinessLogic getComponentInstanceBL(); - - public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText); - - /** - * - * @param componentId - * @param dataParamsToReturn - * @return - */ - public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn); - - protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { - Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext); - ResponseFormat responseFormat; - if (userValidationResult.isRight()) { - user.setUserId("UNKNOWN"); - responseFormat = userValidationResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType()); - return Either.right(responseFormat); - } - Either<User, ResponseFormat> userResult = validateUserExists(user, ecompErrorContext, inTransaction); - if (userResult.isRight()) { - responseFormat = userResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType()); - return Either.right(responseFormat); - } - return userResult; - } - - protected Either<Boolean, ResponseFormat> validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) { - if (roles != null && roles.isEmpty()) { - roles.add(Role.ADMIN); - roles.add(Role.DESIGNER); - } - Either<Boolean, ResponseFormat> validationResult = validateUserRole(user, roles); - if (validationResult.isRight()) { - ComponentTypeEnum componentType = component.getComponentType(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (componentType.equals(ComponentTypeEnum.SERVICE)) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - String distributionStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, distributionStatus); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, distributionStatus); - } - componentsUtils.auditComponent(validationResult.right().value(), user, component, "", "", auditAction, componentType, additionalParams); - } - return validationResult; - } - - protected Either<Boolean, ResponseFormat> validateComponentName(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String componentName = component.getName(); - if (!ValidationUtils.validateStringNotEmpty(componentName)) { - log.debug("component name is empty"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateComponentNameLength(componentName)) { - log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - if (!validateTagPattern(componentName)) { - log.debug("Component name {} has invalid format", componentName); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); - component.setSystemName(ValidationUtils.convertToSystemName(componentName)); - - return Either.left(true); - } - - protected Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String description = component.getDescription(); - if (!ValidationUtils.validateStringNotEmpty(description)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - description = cleanUpText(description); - Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type); - if (validatDescription.isRight()) { - ResponseFormat responseFormat = validatDescription.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - return Either.right(responseFormat); - } - component.setDescription(description); - return Either.left(true); - } - - public Either<Boolean, ResponseFormat> validateComponentDescription(String description, ComponentTypeEnum type) { - if (description != null) { - if (!ValidationUtils.validateDescriptionLength(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); - } - - if (!ValidationUtils.validateIsEnglish(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue())); - } - return Either.left(true); - } - return Either.left(false); - } - - protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - ResourceTypeEnum resourceType = null; - if(component instanceof Resource){ - resourceType = ((Resource)component).getResourceType(); - } - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); - - if (dataModelResponse.isLeft()) { - if ( !dataModelResponse.left().value()) { - return Either.left(true); - } else { - log.info("Component with name {} already exists", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - } - BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); - log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate component contactId"); - ComponentTypeEnum type = component.getComponentType(); - String contactId = component.getContactId(); - - if (!ValidationUtils.validateStringNotEmpty(contactId)) { - log.info("contact is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId, type); - if (validateContactIdResponse.isRight()) { - ResponseFormat responseFormat = validateContactIdResponse.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - } - return validateContactIdResponse; - } - - private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) { - if (contactId != null) { - if (!ValidationUtils.validateContactId(contactId)) { - log.info("contact is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - - public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { - log.trace("validate conformance level"); - - if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.error("conformance level validation for non service component, id {}", componentUuid); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(errorResponse); - } - - Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false); - if (resp.isRight()) { - log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); - return Either.right(resp.right().value()); - } - - Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); - if (eitherComponent.isRight()) { - log.error("can't validate conformance level, component not found, uuid {}", componentUuid); - BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); - - StorageOperationStatus status = eitherComponent.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); - return Either.right(responseFormat); - } - - String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); - if (StringUtils.isBlank(componentConformanceLevel)) { - log.error("component conformance level property is null or empty, uuid {}", componentUuid); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(errorResponse); - } - - String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); - Boolean result = true; - if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { - log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); - result = false; - } - log.trace("conformance level validation finished"); - - return Either.left(result); - } - - protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate Icon"); - ComponentTypeEnum type = component.getComponentType(); - String icon = component.getIcon(); - if (!ValidationUtils.validateStringNotEmpty(icon)) { - log.info("icon is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon, type); - if (validateIcon.isRight()) { - ResponseFormat responseFormat = validateIcon.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - } - return validateIcon; - } - - private Either<Boolean, ResponseFormat> validateIcon(String icon, ComponentTypeEnum type) { - if (icon != null) { - if (!ValidationUtils.validateIconLength(icon)) { - log.debug("icon exceeds max length"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); - } - - if (!ValidationUtils.validateIcon(icon)) { - log.info("icon is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - protected Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) { - List<String> tagsList = component.getTags(); - - Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType()); - if (validateTags.isRight()) { - ResponseFormat responseFormat = validateTags.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType()); - return Either.right(responseFormat); - } - ValidationUtils.removeDuplicateFromList(tagsList); - return Either.left(true); - } - - protected Either<Boolean, ResponseFormat> validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType) { - log.debug("validate component tags"); - boolean includesComponentName = false; - int tagListSize = 0; - if (tags != null && !tags.isEmpty()) { - for (String tag : tags) { - if (!ValidationUtils.validateTagLength(tag)) { - log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); - } - if (validateTagPattern(tag)) { - if (!includesComponentName) { - includesComponentName = name.equals(tag); - } - } else { - log.debug("invalid tag {}", tag); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL)); - } - tagListSize += tag.length() + 1; - } - if (tagListSize > 0) { - tagListSize--; - } - - if (!includesComponentName) { - log.debug("tags must include component name"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME)); - } - if (!ValidationUtils.validateTagListLength(tagListSize)) { - log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); - } - return Either.left(true); - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS)); - } - - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateComponentNamePattern(tag); - } - - protected Either<Boolean, ResponseFormat> validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) { - if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { - return Either.left(true); - } - log.debug("validate ProjectCode name "); - String projectCode = component.getProjectCode(); - - if (!ValidationUtils.validateStringNotEmpty(projectCode)) { - log.info("projectCode is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, component.getComponentType()); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode); - if (validateProjectCodeResponse.isRight()) { - ResponseFormat responseFormat = validateProjectCodeResponse.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType()); - } - return validateProjectCodeResponse; - - } - - private Either<Boolean, ResponseFormat> validateProjectCode(String projectCode) { - if (projectCode != null) { - if (!ValidationUtils.validateProjectCode(projectCode)) { - log.info("projectCode is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - protected void checkComponentFieldsForOverrideAttempt(Component component) { - if (component.getLifecycleState() != null) { - log.info("LifecycleState cannot be defined by user. This field will be overridden by the application"); - } - if (component.getVersion() != null) { - log.info("Version cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getCreatorUserId() != null) || (component.getCreatorFullName() != null)) { - log.info("Creator cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getLastUpdaterUserId() != null) || (component.getLastUpdaterFullName() != null)) { - log.info("Last Updater cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getCreationDate() != null)) { - log.info("Creation Date cannot be defined by user. This field will be overridden by the application"); - } - if ((component.isHighestVersion() != null)) { - log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getUUID() != null)) { - log.info("UUID cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getLastUpdateDate() != null)) { - log.info("Last Update Date cannot be defined by user. This field will be overridden by the application"); - } - if (component.getUniqueId() != null) { - log.info("uid cannot be defined by user. This field will be overridden by the application."); - component.setUniqueId(null); - } - if (component.getInvariantUUID() != null) { - log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application."); - } - } - - protected Either<Boolean, ResponseFormat> validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) { - // validate component name uniqueness - log.debug("validate component name "); - Either<Boolean, ResponseFormat> componentNameValidation = validateComponentName(user, component, actionEnum); - if (componentNameValidation.isRight()) { - return componentNameValidation; - } - - // validate description - log.debug("validate description"); - Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, component, actionEnum); - if (descValidation.isRight()) { - return descValidation; - } - - // validate tags - log.debug("validate tags"); - Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum); - if (tagsValidation.isRight()) { - return tagsValidation; - } - - // validate contact info - log.debug("validate contact info"); - Either<Boolean, ResponseFormat> contactIdValidation = validateContactId(user, component, actionEnum); - if (contactIdValidation.isRight()) { - return contactIdValidation; - } - - // validate icon - log.debug("validate icon"); - Either<Boolean, ResponseFormat> iconValidation = validateIcon(user, component, actionEnum); - if (iconValidation.isRight()) { - return iconValidation; - } - return Either.left(true); - } - - public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<CapReqDef, ResponseFormat> eitherRet = null; - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreRequirements(false); - filter.setIgnoreComponentInstances(false); - Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); - if (eitherComponent.isLeft()) { - eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); - } else { - BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); - eitherRet = Either.right(eitherComponent.right().value()); - } - return eitherRet; - } - - public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids, - String userId) { - ResponseFormat responseFormat = null; - try{ - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - - if (resp.isLeft()) { - List<Component> result = new ArrayList<>(); - List<String> componentsUidToFetch = new ArrayList<>(); - componentsUidToFetch.addAll(componentUids); - - if (!componentsUidToFetch.isEmpty()) { - log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); - Boolean isHighest = isHighest(highestFilter); - Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - result.addAll(nonCheckoutCompResponse.left().value()); - } else { - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); - } - } - return Either.left(result); - } else { - responseFormat = resp.right().value(); - } - } - finally{ - titanDao.commit(); - } - return Either.right(responseFormat); - } - - private Boolean isHighest(HighestFilterEnum highestFilter) { - Boolean isHighest = null; - switch (highestFilter) { - case ALL: - break; - case HIGHEST_ONLY: - isHighest = true; - break; - case NON_HIGHEST_ONLY: - isHighest = false; - break; - default: - break; - } - return isHighest; - } - - public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { - ResponseFormat responseFormat = null; - - try{ - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - if (resp.isLeft()) { - - Boolean isHighest = isHighest(highestFilter); - Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - return Either.left(nonCheckoutCompResponse.left().value()); - } - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); - } else { - responseFormat = resp.right().value(); - } - } finally { - titanDao.commit(); - } - return Either.right(responseFormat); - } - - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - - } - - @SuppressWarnings("unchecked") - public void setToscaArtifactsPlaceHolders(Component component, User user) { - Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<>(); - } - String componentUniqueId = component.getUniqueId(); - String componentSystemName = component.getSystemName(); - String componentType = component.getComponentType().getValue().toLowerCase(); - Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts(); - - if (toscaArtifacts != null) { - for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) { - Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue(); - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA); - artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName"))); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - component.setToscaArtifacts(artifactMap); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { - return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { - Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); - if ( toscaElement.isRight() ){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); - return Either.right(response); - } - component = toscaElement.left().value(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null; - if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { - ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) - .findAny().get(); - generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); - if (generateToscaRes.isRight()) { - return generateToscaRes; - } - toscaArtifact = generateToscaRes.left().value().left().value(); - component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); - if(!isAbstractResource(component)){ - toscaArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) - .findAny().get(); - generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); - if (generateToscaRes.isRight()) { - return generateToscaRes; - } - toscaArtifact = generateToscaRes.left().value().left().value(); - component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); - } - } - return generateToscaRes; - } - - private boolean isAbstractResource(Component component) { - return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); - } - - public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, - boolean inTransaction, boolean fetchTemplatesFromDB) { - return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); - } - - public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) { - - Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); - - if (latestVersionEither.isRight()) { - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); - return Either.right(response); - } - - List<Component> components = latestVersionEither.left().value(); - - Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); - if(component == null){ - component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); - } - - if(component == null){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); - return Either.right(response); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - // TODO remove after migration - handle artifact not found(no - // placeholder) - if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); - } - ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) - .findAny().get(); - return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact); - } - - protected StorageOperationStatus markComponentToDelete(Component component) { - - ComponentTypeEnum componentType = component.getComponentType(); - String uniqueId = component.getUniqueId(); - if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) { - log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType); - return StorageOperationStatus.NOT_FOUND; - } - - StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component); - if (StorageOperationStatus.OK != markResourceToDelete) { - log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete); - return markResourceToDelete; - } else { - log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); - return StorageOperationStatus.OK; - } - } - - public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) { - String descriptionUpdated = updatedComponent.getDescription(); - String descriptionCurrent = currentComponent.getDescription(); - if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) { - Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction); - if (validateDescriptionResponse.isRight()) { - ResponseFormat errorRespons = validateDescriptionResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setDescription(updatedComponent.getDescription()); - } - return Either.left(true); - } - - public Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) { - String projectCodeUpdated = updatedComponent.getProjectCode(); - String projectCodeCurrent = currentComponent.getProjectCode(); - if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) { - Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setProjectCode(updatedComponent.getProjectCode()); - } - return Either.left(true); - } - - public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) { - String iconUpdated = updatedComponent.getIcon(); - String iconCurrent = currentComponent.getIcon(); - if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, updatedComponent, null); - if (validatIconResponse.isRight()) { - ResponseFormat errorRespons = validatIconResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setIcon(updatedComponent.getIcon()); - } else { - log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase()); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { - - log.trace("start deleteMarkedComponents"); - Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); - - titanDao.commit(); - if ( deleteMarkedElements.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); - return Either.right(responseFormat); - } - log.trace("end deleteMarkedComponents"); - return Either.left(deleteMarkedElements.left().value()); - } - - public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) { - List<ArtifactDefinition> artifacts = new ArrayList<>(); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); - if (artifactsResponse.isRight()) { - if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); - return Either.right(artifactsResponse.right().value()); - } - } else { - artifacts.addAll(artifactsResponse.left().value().values()); - } - return Either.left(artifacts); - } - - /** - * - * @param componentId - * @param user - * @param dataParamsToReturn - ui list of params to return - * @return - */ - - public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) { - - if (user != null) { - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - } - - UiComponentDataTransfer result = new UiComponentDataTransfer(); - - if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { - Either.left(result); - - } else { - Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); - if(uiDataTransferEither.isRight()){ - return Either.right(uiDataTransferEither.right().value()); - } - result = uiDataTransferEither.left().value(); - } - - return Either.left(result); - } - - protected <T extends Component> void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) { - List<InputDefinition> genericAndComponentInputs = new ArrayList<>(); - List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); - genericAndComponentInputs.addAll(genericInputs); - if (null != component.getInputs()){ - List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); - genericAndComponentInputs.addAll(nonGenericInputsFromComponent); - } - component.setInputs(genericAndComponentInputs); - } - - private List<InputDefinition> getAllNonGenericInputsFromComponent(List<InputDefinition> genericInputs, List<InputDefinition> componentInputs) { - if (genericInputs == null) { - return componentInputs; - } - - Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); - List<InputDefinition> componentNonGenericInputs = new ArrayList<>(); - componentInputs.stream().forEach(input -> { - if (!inputByNameMap.containsKey(input.getName())) { - componentNonGenericInputs.add(input); - } - }); - return componentNonGenericInputs; - } - - protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){ - Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); - if(genericTypeEither.isRight()){ - log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType())); - } - Resource genericTypeResource = genericTypeEither.left().value(); - component.setDerivedFromGenericInfo(genericTypeResource); - return Either.left(genericTypeResource); - } - - public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) { - Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null; - Either<Component, StorageOperationStatus> getResourceRes = null; - try{ - if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){ - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (userId != null && response == null) { - Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false); - if (validateUserRes.isRight()) { - response = Either.right(validateUserRes.right().value()); - } - } - if(response == null){ - getResourceRes = toscaOperationFacade.getToscaElement(componentId); - if(getResourceRes.isRight()){ - response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); - } - } - if(response == null){ - response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); - } - } catch(Exception e){ - log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId); - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally{ - if (response.isLeft()){ - toscaOperationFacade.commit(); - } else { - toscaOperationFacade.rollback(); - } - } - return response; - } - - private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) { - - Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>(); - Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties); - List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE)); - String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0); - boolean searchByFragment = propertyNameFragment.length() > 3 ; - if(CollectionUtils.isNotEmpty(filteredInstances)){ - for(ComponentInstance instance : filteredInstances){ - if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ - List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); - if(CollectionUtils.isNotEmpty(currProperties)){ - filteredProperties.put(instance.getUniqueId(), currProperties); - } - } - if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ - List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); - if(CollectionUtils.isNotEmpty(currInputs)){ - if(filteredProperties.get(instance.getUniqueId())!=null){ - filteredProperties.get(instance.getUniqueId()).addAll(currInputs); - } else { - filteredProperties.put(instance.getUniqueId(), currInputs); - } - } - } - } - } - return result; - } - - private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) { - return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); - } - - private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) { - return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); - } - - private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) { - boolean isMatching = false; - if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){ - isMatching = true; - } - if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ - isMatching = true; - } - return isMatching; - } - - private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { - boolean isMatching = false; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ - isMatching = true; - } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ - isMatching = true; - } - if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ - isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); - } - return isMatching; - } - - private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { - String propertyType; - List<PropertyDefinition> dataTypeProperties; - DataTypeDefinition currentProperty; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ - return true; - } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ - return true; - } - - propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); - - if(ToscaPropertyType.isScalarType(propertyType)){ - return false; - } - Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); - if(getDataTypeByNameRes.isRight()){ - return false; - } - currentProperty = getDataTypeByNameRes.left().value(); - dataTypeProperties = currentProperty.getProperties(); - - if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } - } - } - dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); - if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } - } - } - return false; - } - - private boolean isEmptyInnerType(PropertyDataDefinition property) { - return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; - } - - public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) { - - if(!clonedComponent.deriveFromGeneric()) - return Either.left(false); - Boolean shouldUpgrade = false; - String currentGenericType = clonedComponent.getDerivedFromGenericType(); - String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); - Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent); - if(fetchAndSetLatestGeneric.isRight()) - return Either.right(fetchAndSetLatestGeneric.right().value()); - Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); - if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ - shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); - if(!shouldUpgrade) { - reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); - } - } - return Either.left(shouldUpgrade); - } - - private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) { - clonedComponent.setDerivedFromGenericType(currentGenericType); - clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); - } - - private <T extends PropertyDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) { - Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList); - Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); - return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); - } - - private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ - - List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties(); - Either<Map<String, PropertyDefinition>, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); - if (validMerge.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); - return false; - } - List<PropertyDefinition> genericTypeAttributes = latestGeneric.getAttributes(); - validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); - if (validMerge.isRight()) { - log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); - return false; - } - return true; - } - + @Autowired + protected ArtifactsBusinessLogic artifactsBusinessLogic; + + @Autowired + protected ComponentCache componentCache; + + @Autowired + private GenericTypeBusinessLogic genericTypeBusinessLogic; + + public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { + this.genericTypeBusinessLogic = genericTypeBusinessLogic; + } + + private static final Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class); + + private static final String TAG_FIELD_LABEL = "tag"; + + public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents(); + + public abstract ComponentInstanceBusinessLogic getComponentInstanceBL(); + + public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText); + + /** + * + * @param componentId + * @param dataParamsToReturn + * @return + */ + public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn); + + protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { + Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext); + ResponseFormat responseFormat; + if (userValidationResult.isRight()) { + user.setUserId("UNKNOWN"); + responseFormat = userValidationResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); + return Either.right(responseFormat); + } + Either<User, ResponseFormat> userResult = validateUserExists(user, ecompErrorContext, inTransaction); + if (userResult.isRight()) { + responseFormat = userResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); + return Either.right(responseFormat); + } + return userResult; + } + + protected Either<Boolean, ResponseFormat> validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) { + if (roles != null && roles.isEmpty()) { + roles.add(Role.ADMIN); + roles.add(Role.DESIGNER); + } + Either<Boolean, ResponseFormat> validationResult = validateUserRole(user, roles); + if (validationResult.isRight()) { + String commentStr = null; + String distrStatus = null; + ComponentTypeEnum componentType = component.getComponentType(); + if (componentType.equals(ComponentTypeEnum.SERVICE)) { + distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); + commentStr = comment; + } + componentsUtils.auditComponent(validationResult.right().value(), user, component, auditAction, componentType, + ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(), + ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(), + null, commentStr, null, null); + + + } + return validationResult; + } + + protected Either<Boolean, ResponseFormat> validateComponentName(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + String componentName = component.getName(); + if (!ValidationUtils.validateStringNotEmpty(componentName)) { + log.debug("component name is empty"); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateComponentNameLength(componentName)) { + log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + if (!validateTagPattern(componentName)) { + log.debug("Component name {} has invalid format", componentName); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); + component.setSystemName(ValidationUtils.convertToSystemName(componentName)); + + return Either.left(true); + } + + protected Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + String description = component.getDescription(); + if (!ValidationUtils.validateStringNotEmpty(description)) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + description = cleanUpText(description); + Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type); + if (validatDescription.isRight()) { + ResponseFormat responseFormat = validatDescription.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + return Either.right(responseFormat); + } + component.setDescription(description); + return Either.left(true); + } + + public Either<Boolean, ResponseFormat> validateComponentDescription(String description, ComponentTypeEnum type) { + if (description != null) { + if (!ValidationUtils.validateDescriptionLength(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); + } + + if (!ValidationUtils.validateIsEnglish(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue())); + } + return Either.left(true); + } + return Either.left(false); + } + + protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + ResourceTypeEnum resourceType = null; + if(component instanceof Resource){ + resourceType = ((Resource)component).getResourceType(); + } + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); + + if (dataModelResponse.isLeft()) { + if ( !dataModelResponse.left().value()) { + return Either.left(true); + } else { + log.info("Component with name {} already exists", component.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + } + BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); + log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) { + log.debug("validate component contactId"); + ComponentTypeEnum type = component.getComponentType(); + String contactId = component.getContactId(); + + if (!ValidationUtils.validateStringNotEmpty(contactId)) { + log.info("contact is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId, type); + if (validateContactIdResponse.isRight()) { + ResponseFormat responseFormat = validateContactIdResponse.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + } + return validateContactIdResponse; + } + + private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) { + if (contactId != null) { + if (!ValidationUtils.validateContactId(contactId)) { + log.info("contact is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + + public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { + log.trace("validate conformance level"); + + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { + log.error("conformance level validation for non service component, id {}", componentUuid); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(errorResponse); + } + + Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false); + if (resp.isRight()) { + log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); + return Either.right(resp.right().value()); + } + + Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); + if (eitherComponent.isRight()) { + log.error("can't validate conformance level, component not found, uuid {}", componentUuid); + BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); + + StorageOperationStatus status = eitherComponent.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Either.right(responseFormat); + } + + String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); + if (StringUtils.isBlank(componentConformanceLevel)) { + log.error("component conformance level property is null or empty, uuid {}", componentUuid); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponse); + } + + String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); + Boolean result = true; + if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { + log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); + result = false; + } + log.trace("conformance level validation finished"); + + return Either.left(result); + } + + protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) { + log.debug("validate Icon"); + ComponentTypeEnum type = component.getComponentType(); + String icon = component.getIcon(); + if (!ValidationUtils.validateStringNotEmpty(icon)) { + log.info("icon is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon, type); + if (validateIcon.isRight()) { + ResponseFormat responseFormat = validateIcon.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + } + return validateIcon; + } + + private Either<Boolean, ResponseFormat> validateIcon(String icon, ComponentTypeEnum type) { + if (icon != null) { + if (!ValidationUtils.validateIconLength(icon)) { + log.debug("icon exceeds max length"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); + } + + if (!ValidationUtils.validateIcon(icon)) { + log.info("icon is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + protected Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) { + List<String> tagsList = component.getTags(); + + Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType()); + if (validateTags.isRight()) { + ResponseFormat responseFormat = validateTags.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType()); + return Either.right(responseFormat); + } + ValidationUtils.removeDuplicateFromList(tagsList); + return Either.left(true); + } + + protected Either<Boolean, ResponseFormat> validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType) { + log.debug("validate component tags"); + boolean includesComponentName = false; + int tagListSize = 0; + if (tags != null && !tags.isEmpty()) { + for (String tag : tags) { + if (!ValidationUtils.validateTagLength(tag)) { + log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); + } + if (validateTagPattern(tag)) { + if (!includesComponentName) { + includesComponentName = name.equals(tag); + } + } else { + log.debug("invalid tag {}", tag); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL)); + } + tagListSize += tag.length() + 1; + } + if (tagListSize > 0) { + tagListSize--; + } + + if (!includesComponentName) { + log.debug("tags must include component name"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME)); + } + if (!ValidationUtils.validateTagListLength(tagListSize)) { + log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); + } + return Either.left(true); + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS)); + } + + protected boolean validateTagPattern(String tag) { + return ValidationUtils.validateComponentNamePattern(tag); + } + + protected Either<Boolean, ResponseFormat> validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) { + if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { + return Either.left(true); + } + log.debug("validate ProjectCode name "); + String projectCode = component.getProjectCode(); + + if (!ValidationUtils.validateStringNotEmpty(projectCode)) { + log.info("projectCode is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build()); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode); + if (validateProjectCodeResponse.isRight()) { + ResponseFormat responseFormat = validateProjectCodeResponse.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build()); + } + return validateProjectCodeResponse; + + } + + private Either<Boolean, ResponseFormat> validateProjectCode(String projectCode) { + if (projectCode != null) { + if (!ValidationUtils.validateProjectCode(projectCode)) { + log.info("projectCode is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + protected void checkComponentFieldsForOverrideAttempt(Component component) { + if (component.getLifecycleState() != null) { + log.info("LifecycleState cannot be defined by user. This field will be overridden by the application"); + } + if (component.getVersion() != null) { + log.info("Version cannot be defined by user. This field will be overridden by the application"); + } + if (component.getCreatorUserId() != null || component.getCreatorFullName() != null) { + log.info("Creator cannot be defined by user. This field will be overridden by the application"); + } + if (component.getLastUpdaterUserId() != null || component.getLastUpdaterFullName() != null) { + log.info("Last Updater cannot be defined by user. This field will be overridden by the application"); + } + if (component.getCreationDate() != null) { + log.info("Creation Date cannot be defined by user. This field will be overridden by the application"); + } + if (component.isHighestVersion() != null) { + log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application"); + } + if (component.getUUID() != null) { + log.info("UUID cannot be defined by user. This field will be overridden by the application"); + } + if (component.getLastUpdateDate() != null) { + log.info("Last Update Date cannot be defined by user. This field will be overridden by the application"); + } + if (component.getUniqueId() != null) { + log.info("uid cannot be defined by user. This field will be overridden by the application."); + component.setUniqueId(null); + } + if (component.getInvariantUUID() != null) { + log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application."); + } + } + + protected Either<Boolean, ResponseFormat> validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) { + // validate component name uniqueness + log.debug("validate component name "); + Either<Boolean, ResponseFormat> componentNameValidation = validateComponentName(user, component, actionEnum); + if (componentNameValidation.isRight()) { + return componentNameValidation; + } + + // validate description + log.debug("validate description"); + Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, component, actionEnum); + if (descValidation.isRight()) { + return descValidation; + } + + // validate tags + log.debug("validate tags"); + Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum); + if (tagsValidation.isRight()) { + return tagsValidation; + } + + // validate contact info + log.debug("validate contact info"); + Either<Boolean, ResponseFormat> contactIdValidation = validateContactId(user, component, actionEnum); + if (contactIdValidation.isRight()) { + return contactIdValidation; + } + + // validate icon + log.debug("validate icon"); + Either<Boolean, ResponseFormat> iconValidation = validateIcon(user, component, actionEnum); + if (iconValidation.isRight()) { + return iconValidation; + } + return Either.left(true); + } + + public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<CapReqDef, ResponseFormat> eitherRet = null; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreComponentInstances(false); + Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); + if (eitherComponent.isLeft()) { + eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); + } else { + BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); + eitherRet = Either.right(eitherComponent.right().value()); + } + return eitherRet; + } + + public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids, + String userId) { + ResponseFormat responseFormat = null; + try{ + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + + if (resp.isLeft()) { + List<Component> result = new ArrayList<>(); + List<String> componentsUidToFetch = new ArrayList<>(); + componentsUidToFetch.addAll(componentUids); + + if (!componentsUidToFetch.isEmpty()) { + log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); + Boolean isHighest = isHighest(highestFilter); + Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + result.addAll(nonCheckoutCompResponse.left().value()); + } else { + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } + } + return Either.left(result); + } else { + responseFormat = resp.right().value(); + } + } + finally{ + titanDao.commit(); + } + return Either.right(responseFormat); + } + + private Boolean isHighest(HighestFilterEnum highestFilter) { + Boolean isHighest = null; + switch (highestFilter) { + case ALL: + break; + case HIGHEST_ONLY: + isHighest = true; + break; + case NON_HIGHEST_ONLY: + isHighest = false; + break; + default: + break; + } + return isHighest; + } + + public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { + ResponseFormat responseFormat = null; + + try{ + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + if (resp.isLeft()) { + + Boolean isHighest = isHighest(highestFilter); + Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + return Either.left(nonCheckoutCompResponse.left().value()); + } + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } else { + responseFormat = resp.right().value(); + } + } finally { + titanDao.commit(); + } + return Either.right(responseFormat); + } + + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + + } + + @SuppressWarnings("unchecked") + public void setToscaArtifactsPlaceHolders(Component component, User user) { + Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<>(); + } + String componentUniqueId = component.getUniqueId(); + String componentSystemName = component.getSystemName(); + String componentType = component.getComponentType().getValue().toLowerCase(); + Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts(); + + if (toscaArtifacts != null) { + for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) { + Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue(); + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA); + artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName"))); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + component.setToscaArtifacts(artifactMap); + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { + return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { + Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); + if ( toscaElement.isRight() ){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); + return Either.right(response); + } + component = toscaElement.left().value(); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null; + if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { + ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) + .findAny().get(); + generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); + if (generateToscaRes.isRight()) { + return generateToscaRes; + } + toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); + if(!isAbstractResource(component)){ + toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); + generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); + if (generateToscaRes.isRight()) { + return generateToscaRes; + } + toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); + } + } + return generateToscaRes; + } + + private boolean isAbstractResource(Component component) { + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); + } + + public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, + boolean inTransaction, boolean fetchTemplatesFromDB) { + return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); + } + + public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) { + + Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null); + + if (latestVersionEither.isRight()) { + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); + return Either.right(response); + } + + List<Component> components = latestVersionEither.left().value(); + + Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); + if(component == null){ + component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); + } + + if(component == null){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); + return Either.right(response); + } + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + // TODO remove after migration - handle artifact not found(no + // placeholder) + if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); + } + ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); + return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact); + } + + protected StorageOperationStatus markComponentToDelete(Component component) { + + ComponentTypeEnum componentType = component.getComponentType(); + String uniqueId = component.getUniqueId(); + if (Boolean.TRUE.equals(component.getIsDeleted())) { + log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType); + return StorageOperationStatus.NOT_FOUND; + } + + StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component); + if (StorageOperationStatus.OK != markResourceToDelete) { + log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete); + return markResourceToDelete; + } else { + log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); + return StorageOperationStatus.OK; + } + } + + public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) { + String descriptionUpdated = updatedComponent.getDescription(); + String descriptionCurrent = currentComponent.getDescription(); + if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) { + Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction); + if (validateDescriptionResponse.isRight()) { + ResponseFormat errorRespons = validateDescriptionResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setDescription(updatedComponent.getDescription()); + } + return Either.left(true); + } + + public Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) { + String projectCodeUpdated = updatedComponent.getProjectCode(); + String projectCodeCurrent = currentComponent.getProjectCode(); + if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) { + Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null); + if (validatProjectCodeResponse.isRight()) { + ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setProjectCode(updatedComponent.getProjectCode()); + } + return Either.left(true); + } + + public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) { + String iconUpdated = updatedComponent.getIcon(); + String iconCurrent = currentComponent.getIcon(); + if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, updatedComponent, null); + if (validatIconResponse.isRight()) { + ResponseFormat errorRespons = validatIconResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setIcon(updatedComponent.getIcon()); + } else { + log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase()); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { + + log.trace("start deleteMarkedComponents"); + Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); + + titanDao.commit(); + if ( deleteMarkedElements.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); + return Either.right(responseFormat); + } + log.trace("end deleteMarkedComponents"); + return Either.left(deleteMarkedElements.left().value()); + } + + public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) { + List<ArtifactDefinition> artifacts = new ArrayList<>(); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); + if (artifactsResponse.isRight()) { + if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); + return Either.right(artifactsResponse.right().value()); + } + } else { + artifacts.addAll(artifactsResponse.left().value().values()); + } + return Either.left(artifacts); + } + + /** + * + * @param componentId + * @param user + * @param dataParamsToReturn - ui list of params to return + * @return + */ + + public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) { + + if (user != null) { + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + } + + UiComponentDataTransfer result = new UiComponentDataTransfer(); + + if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { + Either.left(result); + + } else { + Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); + if(uiDataTransferEither.isRight()){ + return Either.right(uiDataTransferEither.right().value()); + } + result = uiDataTransferEither.left().value(); + } + + return Either.left(result); + } + + protected <T extends Component> void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) { + List<InputDefinition> genericAndComponentInputs = new ArrayList<>(); + List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); + genericAndComponentInputs.addAll(genericInputs); + if (null != component.getInputs()){ + List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); + genericAndComponentInputs.addAll(nonGenericInputsFromComponent); + } + component.setInputs(genericAndComponentInputs); + } + + private List<InputDefinition> getAllNonGenericInputsFromComponent(List<InputDefinition> genericInputs, List<InputDefinition> componentInputs) { + if (genericInputs == null) { + return componentInputs; + } + + Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); + List<InputDefinition> componentNonGenericInputs = new ArrayList<>(); + componentInputs.stream().forEach(input -> { + if (!inputByNameMap.containsKey(input.getName())) { + componentNonGenericInputs.add(input); + } + }); + return componentNonGenericInputs; + } + + protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){ + Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); + if(genericTypeEither.isRight()){ + log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType())); + } + Resource genericTypeResource = genericTypeEither.left().value(); + component.setDerivedFromGenericInfo(genericTypeResource); + return Either.left(genericTypeResource); + } + + public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) { + Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null; + Either<Component, StorageOperationStatus> getResourceRes = null; + try{ + if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){ + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (userId != null && response == null) { + Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false); + if (validateUserRes.isRight()) { + response = Either.right(validateUserRes.right().value()); + } + } + if(response == null){ + getResourceRes = toscaOperationFacade.getToscaElement(componentId); + if(getResourceRes.isRight()){ + response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); + } + } + if(response == null){ + response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); + } + } catch(Exception e){ + log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId); + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally{ + if (response.isLeft()){ + toscaOperationFacade.commit(); + } else { + toscaOperationFacade.rollback(); + } + } + return response; + } + + private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) { + + Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>(); + Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties); + List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE)); + String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0); + boolean searchByFragment = propertyNameFragment.length() > 3 ; + if(CollectionUtils.isNotEmpty(filteredInstances)){ + for(ComponentInstance instance : filteredInstances){ + if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ + List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currProperties)){ + filteredProperties.put(instance.getUniqueId(), currProperties); + } + } + if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ + List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currInputs)){ + if(filteredProperties.get(instance.getUniqueId())!=null){ + filteredProperties.get(instance.getUniqueId()).addAll(currInputs); + } else { + filteredProperties.put(instance.getUniqueId(), currInputs); + } + } + } + } + } + return result; + } + + private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) { + return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) { + return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + return isMatching; + } + + private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ + isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); + } + return isMatching; + } + + private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { + String propertyType; + List<PropertyDefinition> dataTypeProperties; + DataTypeDefinition currentProperty; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ + return true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + return true; + } + + propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); + + if(ToscaPropertyType.isScalarType(propertyType)){ + return false; + } + Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); + if(getDataTypeByNameRes.isRight()){ + return false; + } + currentProperty = getDataTypeByNameRes.left().value(); + dataTypeProperties = currentProperty.getProperties(); + + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + return false; + } + + private boolean isEmptyInnerType(PropertyDataDefinition property) { + return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; + } + + public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) { + + if(!clonedComponent.deriveFromGeneric()) + return Either.left(false); + Boolean shouldUpgrade = false; + String currentGenericType = clonedComponent.getDerivedFromGenericType(); + String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); + Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent); + if(fetchAndSetLatestGeneric.isRight()) + return Either.right(fetchAndSetLatestGeneric.right().value()); + Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); + if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ + shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); + if(!shouldUpgrade) { + reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); + } + } + return Either.left(shouldUpgrade); + } + + private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) { + clonedComponent.setDerivedFromGenericType(currentGenericType); + clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); + } + + private <T extends PropertyDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) { + Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList); + Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); + return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); + } + + private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ + + List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties(); + Either<Map<String, PropertyDefinition>, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + if (validMerge.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + List<PropertyDefinition> genericTypeAttributes = latestGeneric.getAttributes(); + validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); + if (validMerge.isRight()) { + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + return true; + } + private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) { - - if (!componentToCheckOut.shouldGenerateInputs()) { - //node type - validate properties and attributes - return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); - } - List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties(); - List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); - List<InputDefinition> currentList = new ArrayList<>(); - // nullify existing ownerId from existing list and merge into updated list - if (null != componentToCheckOut.getInputs()) { - for(InputDefinition input : componentToCheckOut.getInputs()) { - InputDefinition copy = new InputDefinition(input); - copy.setOwnerId(null); - currentList.add(copy); - } - } - if (null == genericTypeInputs) { - componentToCheckOut.setInputs(currentList); - return true; - } - - Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); - if (eitherMerged.isRight()) { - log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); - return false; - } - componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values())); - return true; - } - - - private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) { - List<ComponentInstance> filteredInstances = null; - if(CollectionUtils.isEmpty(resourceTypes)){ - filteredInstances = component.getComponentInstances(); - } - else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ - filteredInstances = component.getComponentInstances() - .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); - } - if(filteredInstances == null){ - filteredInstances = new ArrayList<>(); - } - return filteredInstances; - } - - private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) { - boolean isMatchingType = false; - for(String resourceType : resourceTypes){ - if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ - isMatchingType = true; - break; - } - } - return isMatchingType; - } - - protected String cleanUpText(String text){ - text = ValidationUtils.removeNoneUtf8Chars(text); - text = ValidationUtils.normaliseWhitespace(text); - text = ValidationUtils.stripOctets(text); - text = ValidationUtils.removeHtmlTagsOnly(text); - return text; - } - - public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { - //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override - return Either.right(ActionStatus.GENERAL_ERROR); - } + + if (!componentToCheckOut.shouldGenerateInputs()) { + //node type - validate properties and attributes + return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); + } + List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties(); + List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); + List<InputDefinition> currentList = new ArrayList<>(); + // nullify existing ownerId from existing list and merge into updated list + if (null != componentToCheckOut.getInputs()) { + for(InputDefinition input : componentToCheckOut.getInputs()) { + InputDefinition copy = new InputDefinition(input); + copy.setOwnerId(null); + currentList.add(copy); + } + } + if (null == genericTypeInputs) { + componentToCheckOut.setInputs(currentList); + return true; + } + + Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); + if (eitherMerged.isRight()) { + log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); + return false; + } + componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values())); + return true; + } + + + private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) { + List<ComponentInstance> filteredInstances = null; + if(CollectionUtils.isEmpty(resourceTypes)){ + filteredInstances = component.getComponentInstances(); + } + else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + filteredInstances = component.getComponentInstances() + .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); + } + if(filteredInstances == null){ + filteredInstances = new ArrayList<>(); + } + return filteredInstances; + } + + private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) { + boolean isMatchingType = false; + for(String resourceType : resourceTypes){ + if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ + isMatchingType = true; + break; + } + } + return isMatchingType; + } + + protected String cleanUpText(String text){ + text = ValidationUtils.removeNoneUtf8Chars(text); + text = ValidationUtils.normaliseWhitespace(text); + text = ValidationUtils.stripOctets(text); + text = ValidationUtils.removeHtmlTagsOnly(text); + return text; + } + + public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { + //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override + return Either.right(ActionStatus.GENERAL_ERROR); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index b86b28a6c5..2eca73c560 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -20,25 +20,16 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.google.common.collect.Sets; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.version.PostChangeVersionOperationOrchestrator; import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic; import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -46,6 +37,8 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; @@ -53,25 +46,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; @@ -92,286 +70,369 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; -public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { - - private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName()); - - @Autowired - private IComponentInstanceOperation componentInstanceOperation; - - @Autowired - private ArtifactsBusinessLogic artifactBusinessLogic; - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; - - public static final String VF_MODULE = "org.openecomp.groups.VfModule"; - - public ComponentInstanceBusinessLogic() { - } - - public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { - return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); - } - - public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { - - Component origComponent = null; - Either<ComponentInstance, ResponseFormat> resultOp = null; - User user = null; - org.openecomp.sdc.be.model.Component containerComponent = null; - ComponentTypeEnum containerComponentType; - - try { - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } else { - user = resp.left().value(); - } - - Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); - if (validateValidJson.isRight()) { - return Either.right(validateValidJson.right().value()); - } - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } else { - containerComponentType = validateComponentType.left().value(); - } - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } else { - containerComponent = validateComponentExists.left().value(); - } - - if (ModelConverter.isAtomicComponent(containerComponent)) { - log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); - } - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - if (resourceInstance != null && containerComponentType != null) { - OriginTypeEnum originType = resourceInstance.getOriginType(); - if (originType == OriginTypeEnum.ServiceProxy) { - Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); - } - origComponent = serviceProxyOrigin.left().value(); - - StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } - - } else { - Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); - - if (getOriginComponentRes.isRight()) { - return Either.right(getOriginComponentRes.right().value()); - } else { - origComponent = getOriginComponentRes.left().value(); - } - } - } - if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - log.debug("Try to create entry on graph"); - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { - resourceInstance.setIsProxy(true); - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreCapabiltyProperties(false); - filter.setIgnoreComponentInstances(false); - filter.setIgnoreRequirements(false); - Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); - if (serviceRes.isRight()) { - return serviceRes.right().value(); - } - Component service = serviceRes.left().value(); - Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities(); - resourceInstance.setCapabilities(capabilities); - Map<String, List<RequirementDefinition>> req = service.getRequirements(); - resourceInstance.setRequirements(req); - - String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; - String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); - int lastIndexOf = toscaResourceName.lastIndexOf('.'); - if (lastIndexOf != -1) { - String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name; - resourceInstance.setToscaComponentName(proxyToscaName); - } - resourceInstance.setName(name); - resourceInstance.setIsProxy(true); - resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); - resourceInstance.setSourceModelName(service.getName()); - resourceInstance.setSourceModelUuid(service.getUUID()); - resourceInstance.setSourceModelUid(service.getUniqueId()); - resourceInstance.setComponentUid(proxyTemplate.getUniqueId()); - resourceInstance.setDescription("A Proxy for Service " + service.getName()); - resourceInstance.setComponentVersion(service.getVersion()); - - return StorageOperationStatus.OK; - } - - public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { - - Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null; - ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); - RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - User user = resp.left().value(); - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - if (ModelConverter.isAtomicComponent(containerComponent)) { - log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); - } - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - - try { - log.debug("Try to create entry on graph"); - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance, true); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component origComponent = eitherResourceName.left().value(); - - Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - if (result.isRight()) { - log.debug("Failed to create resource instance {}", containerComponentId); - resultOp = Either.right(result.right().value()); - return resultOp; - - } - - log.debug("Entity on graph is created."); - ComponentInstance resResourceInfo = result.left().value(); - if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { - associationInfo.setFromNode(resResourceInfo.getUniqueId()); - } else { - associationInfo.setToNode(resResourceInfo.getUniqueId()); - } - - RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo); - Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); - if (resultReqCapDef.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); - CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef); - resultOp = Either.left(resInfo); - return resultOp; - - } else { - log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null)); - return resultOp; - } - - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) { - Either<Component, ResponseFormat> eitherResponse; - Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); - if (eitherComponent.isRight()) { - log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName()); - eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); - } else { - eitherResponse = Either.left(eitherComponent.left().value()); - } - return eitherResponse; - } - - private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { - Either<ComponentInstance, ResponseFormat> resultOp; - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); - - if (result.isRight()) { - log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); - return resultOp; - } - - log.debug("Entity on graph is created."); - Component updatedComponent = result.left().value().getLeft(); - Map<String, String> existingEnvVersions = new HashMap<>(); - // TODO existingEnvVersions ?? - Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); - if (addComponentInstanceArtifacts.isRight()) { - log.debug("Failed to create component instance {}", componentInstance.getName()); - resultOp = Either.right(addComponentInstanceArtifacts.right().value()); - return resultOp; - } - - Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); - if (!updatedInstanceOptional.isPresent()) { - log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - return resultOp; - } - resultOp = Either.left(updatedInstanceOptional.get()); - return resultOp; - } +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + +@org.springframework.stereotype.Component +public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class); + + @Autowired + private IComponentInstanceOperation componentInstanceOperation; + + @Autowired + private ArtifactsBusinessLogic artifactBusinessLogic; + + @Autowired + private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; + + @Autowired + private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator; + + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; + + public ComponentInstanceBusinessLogic() { + } + + public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { + return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); + } + + public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List<ComponentInstanceProperty> resList = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties(); + if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){ + ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() { + @Override + public void accept(String s, List<ComponentInstanceProperty> ciPropList) { + String ciName = ""; + Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceProperty prop: ciPropList){ + List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List<ComponentInstanceInput> resList = new ArrayList<>(); + Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs(); + if(ciInputsMap != null && !ciInputsMap.isEmpty()){ + ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() { + @Override + public void accept(String s, List<ComponentInstanceInput> ciPropList) { + String ciName = ""; + Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceInput prop: ciPropList){ + List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { + + Component origComponent = null; + Either<ComponentInstance, ResponseFormat> resultOp = null; + User user = null; + org.openecomp.sdc.be.model.Component containerComponent = null; + ComponentTypeEnum containerComponentType; + + try { + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } else { + user = resp.left().value(); + } + + Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); + if (validateValidJson.isRight()) { + return Either.right(validateValidJson.right().value()); + } + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } else { + containerComponentType = validateComponentType.left().value(); + } + + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } else { + containerComponent = validateComponentExists.left().value(); + } + + if (ModelConverter.isAtomicComponent(containerComponent)) { + log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); + } + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + if (resourceInstance != null && containerComponentType != null) { + OriginTypeEnum originType = resourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); + + StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); + + } + + } else { + Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); + + if (getOriginComponentRes.isRight()) { + return Either.right(getOriginComponentRes.right().value()); + } else { + origComponent = getOriginComponentRes.left().value(); + } + } + } + if (needLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + log.debug("Try to create entry on graph"); + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { + resourceInstance.setIsProxy(true); + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreRequirements(false); + Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); + if (serviceRes.isRight()) { + return serviceRes.right().value(); + } + Component service = serviceRes.left().value(); + Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities(); + resourceInstance.setCapabilities(capabilities); + Map<String, List<RequirementDefinition>> req = service.getRequirements(); + resourceInstance.setRequirements(req); + + String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; + String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); + int lastIndexOf = toscaResourceName.lastIndexOf('.'); + if (lastIndexOf != -1) { + String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name; + resourceInstance.setToscaComponentName(proxyToscaName); + } + resourceInstance.setName(name); + resourceInstance.setIsProxy(true); + resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); + resourceInstance.setSourceModelName(service.getName()); + resourceInstance.setSourceModelUuid(service.getUUID()); + resourceInstance.setSourceModelUid(service.getUniqueId()); + resourceInstance.setComponentUid(proxyTemplate.getUniqueId()); + resourceInstance.setDescription("A Proxy for Service " + service.getName()); + resourceInstance.setComponentVersion(service.getVersion()); + + return StorageOperationStatus.OK; + } + + public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { + + Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null; + ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); + RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + User user = resp.left().value(); + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + if (ModelConverter.isAtomicComponent(containerComponent)) { + log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); + } + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + + try { + log.debug("Try to create entry on graph"); + Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component origComponent = eitherResourceName.left().value(); + + Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); + if (result.isRight()) { + log.debug("Failed to create resource instance {}", containerComponentId); + resultOp = Either.right(result.right().value()); + return resultOp; + + } + + log.debug("Entity on graph is created."); + ComponentInstance resResourceInfo = result.left().value(); + if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { + associationInfo.setFromNode(resResourceInfo.getUniqueId()); + } else { + associationInfo.setToNode(resResourceInfo.getUniqueId()); + } + + RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo; + Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); + if (resultReqCapDef.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); + CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef); + resultOp = Either.left(resInfo); + return resultOp; + + } else { + log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null)); + return resultOp; + } + + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) { + return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid()); + } + + private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) { + return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid()); + } + + private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) { + Either<Component, ResponseFormat> eitherResponse; + Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId); + if (eitherComponent.isRight()) { + log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName); + eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); + } else { + eitherResponse = Either.left(eitherComponent.left().value()); + } + return eitherResponse; + } + + private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { + Either<ComponentInstance, ResponseFormat> resultOp; + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); + + if (result.isRight()) { + log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); + return resultOp; + } + + log.debug("Entity on graph is created."); + Component updatedComponent = result.left().value().getLeft(); + Map<String, String> existingEnvVersions = new HashMap<>(); + // TODO existingEnvVersions ?? + Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); + if (addComponentInstanceArtifacts.isRight()) { + log.debug("Failed to create component instance {}", componentInstance.getName()); + resultOp = Either.right(addComponentInstanceArtifacts.right().value()); + return resultOp; + } + + Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + return resultOp; + } + resultOp = Either.left(updatedInstanceOptional.get()); + return resultOp; + } /** * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts @@ -382,2012 +443,2196 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param existingEnvVersions * @return */ - protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) { - - log.debug("add artifacts to resource instance"); - List<GroupDefinition> filteredGroups = null; - ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); - if (!ActionStatus.OK.equals(status)) { - ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); - return Either.right(resultOp); - } - StorageOperationStatus artStatus; - // generate heat_env if necessary - Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { - - Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(); - Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>(); - - for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { - String type = artifact.getArtifactType(); - if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - } - if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { - continue; - } - if (artifact.checkEsIdExist()) { - Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, - componentInstance.getName(), user, containerComponent, existingEnvVersions); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); - // put env - finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - if (CollectionUtils.isNotEmpty(originComponent.getGroups())) { - filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); - } - if (CollectionUtils.isNotEmpty(filteredGroups)) { - for (GroupDefinition groupInstance : filteredGroups) { - Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); - if (op.isPresent()) { - List<ArtifactDefinition> artifactsUid; - if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { - artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); - } else { - artifactsUid = new ArrayList<>(); - } - artifactsUid.add(artifactDefinition); - groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); - break; - } - } - } - } - } - artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); - if (artStatus != StorageOperationStatus.OK) { - log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - - } - StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); - if (result != StorageOperationStatus.OK) { - log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); - } - componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); - } - - artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); - if (artStatus != StorageOperationStatus.OK) { - log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - - } - componentInstance.setArtifacts(originComponent.getArtifacts()); - return Either.left(ActionStatus.OK); - } - - private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null); - - Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>(); - if (getResourceDeploymentArtifacts.isRight()) { - StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); - if (!status.equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); - return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); - } - } else { - deploymentArtifacts = getResourceDeploymentArtifacts.left().value(); - } - - if (!deploymentArtifacts.isEmpty()) { - Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts); - for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) { - if (!artifact.getValue().checkEsIdExist()) { - tempDeploymentArtifacts.remove(artifact.getKey()); - } - } - - resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts); - } - - return ActionStatus.OK; - } - - public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { - return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); - } - - public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, - boolean needLock, boolean createNewTransaction) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<ComponentInstance, ResponseFormat> resultOp = null; - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - ComponentTypeEnum instanceType = getComponentType(containerComponentType); - Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); - if (validateParentStatus.isRight()) { - log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); - return resultOp; - } - if (!validateParentStatus.left().value()) { - resultOp = Either.right( - componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); - return resultOp; - } - - if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - try { - - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance, inTransaction); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component origComponent = eitherResourceName.left().value(); - - resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - // New Multiple Instance Update API - public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock, - boolean createNewTransaction) { - - Either<List<ComponentInstance>, ResponseFormat> resultOp = null; - org.openecomp.sdc.be.model.Component containerComponent = null; - try { - Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - ComponentParametersView componentFilter = new ComponentParametersView(); - componentFilter.disableAll(); - componentFilter.setIgnoreUsers(false); - componentFilter.setIgnoreComponentInstances(false); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - - containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - ComponentTypeEnum instanceType = getComponentType(containerComponentType); - - for (ComponentInstance componentInstance : componentInstanceList) { - boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); - if (!validateParent) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), - containerComponentId)); - return resultOp; - } - } - - if (needLock) { - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List<ComponentInstance> updatedList = new ArrayList<>(); - List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances(); - List<ComponentInstance> listForUpdate = new ArrayList<>(); - if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) - containerComponent.setComponentInstances(componentInstanceList); - else { - Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator(); - while (iterator.hasNext()) { - ComponentInstance origInst = iterator.next(); - Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); - if (op.isPresent()) { - ComponentInstance updatedCi = op.get(); - updatedCi = buildComponentInstance(updatedCi, origInst); - - Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); - if (!isUniqueName) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); - return resultOp; - } - - listForUpdate.add(updatedCi); - } else - listForUpdate.add(origInst); - } - containerComponent.setComponentInstances(listForUpdate); - - if (resultOp == null) { - Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); - if (updateStatus.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); - return resultOp; - } - for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { - Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); - if (op.isPresent()) { - updatedList.add(updatedInstance); - } - } - } - } - - resultOp = Either.left(updatedList); - return resultOp; - - } finally { - if (needLock) { - unlockComponent(resultOp, containerComponent); - } - } - } - - private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) { - return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId)); - } - - private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { - if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { - return ComponentTypeEnum.SERVICE_INSTANCE; - } else { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } - } - - private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, - ComponentInstance componentInstance) { - - Either<ComponentInstance, ResponseFormat> resultOp = null; - Optional<ComponentInstance> componentInstanceOptional = null; - Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null; - ComponentInstance oldComponentInstance = null; - boolean isNameChanged = false; - - if (resultOp == null) { - componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); - if (!componentInstanceOptional.isPresent()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } - } - if (resultOp == null) { - oldComponentInstance = componentInstanceOptional.get(); - String newInstanceName = componentInstance.getName(); - if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) - isNameChanged = true; - Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); - if (!isUniqueName) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); - } - } - if (resultOp == null) { - updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); - if (updateRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), - updateRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); - } else { - // region - Update instance Groups - if (isNameChanged) { - Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); - if (result.isRight()) - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); - } - // endregion - } - } - if (resultOp == null) { - String newInstanceId = updateRes.left().value().getRight(); - Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); - - if (!updatedInstanceOptional.isPresent()) { - log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } else { - resultOp = Either.left(updatedInstanceOptional.get()); - } - - } - if (resultOp == null) { - resultOp = Either.left(componentInstanceOptional.get()); - } - return resultOp; - } - - /** - * @param oldPrefix- - * The normalized old vf name - * @param newNormailzedPrefix- - * The normalized new vf name - * @param qualifiedGroupInstanceName- - * old Group Instance Name - **/ - // modify group names - private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) { - if (qualifiedGroupInstanceName == null) { - log.info("CANNOT change group name "); - return null; - } - if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) - return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix); - return qualifiedGroupInstanceName; - } - - private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) { - oldComponentInstance.setName(newComponentInstance.getName()); - oldComponentInstance.setModificationTime(System.currentTimeMillis()); - oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); - if (oldComponentInstance.getGroupInstances() != null) - oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); - return oldComponentInstance; - } - - public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - // validate resource - /* - * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils - * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) { - * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } - */ - Either<ComponentInstance, ResponseFormat> resultOp = null; - try { - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - return resultOp; - - } finally { - /* - * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service); - */ - unlockComponent(resultOp, containerComponent); - } - } - - private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { - - Either<ComponentInstance, ResponseFormat> resultOp = null; - ComponentInstance deletedInstance = null; - Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); - - if (deleteRes.isRight()) { - log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } - if (resultOp == null) { - log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); - deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); - resultOp = Either.left(deletedInstance); - } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { - List<GroupDataDefinition> groupsToUpdate = new ArrayList<>(); - for (GroupDataDefinition currGroup : containerComponent.getGroups()) { - Map<String, String> members = currGroup.getMembers(); - if (members != null && members.containsKey(deletedInstance.getName())) { - members.remove(deletedInstance.getName()); - groupsToUpdate.add(currGroup); - } - } - Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate); - if (updateGroupsRes.isRight()) { - log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } - } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { - List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); - if (CollectionUtils.isNotEmpty(inputsToDelete)) { - StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); - if (deleteInputsRes != StorageOperationStatus.OK) { - log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); - } - } - } - return resultOp; - } - - private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { - ComponentInstance foundInstance = null; - for (ComponentInstance instance : containerComponent.getComponentInstances()) { - if (instance.getUniqueId().equals(componentInstanceId)) { - foundInstance = instance; - containerComponent.getComponentInstances().remove(instance); - break; - } - } - return foundInstance; - } - - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true); - } - - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock, - boolean createNewTransaction) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - if (needLock) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - try { - - resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); - - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { - - log.debug("Try to create entry on graph"); - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - - Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); - - if (result.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; - - } else { - log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); - String fromNameOrId = ""; - String toNameOrId = ""; - Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); - Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - - toNameOrId = requirementDef.getFromNode(); - fromNameOrId = requirementDef.getFromNode(); - if (fromResult.isLeft()) { - fromNameOrId = fromResult.left().value().getName(); - } - if (toResult.isLeft()) { - toNameOrId = toResult.left().value().getName(); - } - - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - - return resultOp; - } - - } - - public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - try { - log.debug("Try to create entry on graph"); - Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); - if (result.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; - - } else { - - log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); - String fromNameOrId = ""; - String toNameOrId = ""; - Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); - Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - - toNameOrId = requirementDef.getFromNode(); - fromNameOrId = requirementDef.getFromNode(); - if (fromResult.isLeft()) { - fromNameOrId = fromResult.left().value().getName(); - } - if (toResult.isLeft()) { - toNameOrId = toResult.left().value().getName(); - } - - resultOp = Either - .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - return resultOp; - } - } finally { - unlockComponent(resultOp, containerComponent); - } - } - /** - * Allows to get relation contained in specified component according to received Id - * @param componentId - * @param relationId - * @param userId - * @param componentTypeEnum - * @return - */ - public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) { - - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; - try { - org.openecomp.sdc.be.model.Component containerComponent = null; - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null; - RequirementCapabilityRelDef foundRelation = null; - - Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false); - if (validateUserRes.isRight()) { - resultOp = Either.right(validateUserRes.right().value()); - } - if(resultOp == null){ - validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - resultOp = Either.right(validateComponentExists.right().value()); - } - } - if(resultOp == null){ - containerComponent = validateComponentExists.left().value(); - List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); - foundRelation = findRelation(relationId, requirementCapabilityRelations); - if(foundRelation == null){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); - log.debug("Relation with id {} was not found on the component", relationId, componentId); - resultOp = Either.right(responseFormat); - } - } - if(resultOp == null){ - resultOp = setRelatedCapability(foundRelation, containerComponent); - } - if(resultOp.isLeft()){ - resultOp = setRelatedRequirement(foundRelation, containerComponent); - } - } catch (Exception e) { - log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return resultOp; - } - - private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) { - for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ - if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){ - return relationship; - } - } - return null; - } - - private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { - Either<RequirementCapabilityRelDef, ResponseFormat> result = null; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); - String instanceId = foundRelation.getFromNode(); - Optional<RequirementDefinition> foundRequirement; - Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instance.isPresent()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); - log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } - if(result == null){ - for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){ - foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); - if(foundRequirement.isPresent()){ - foundRelation.getSingleRelationship().setRequirement(foundRequirement.get()); - result = Either.left(foundRelation); - } - } - } - if(result == null){ - Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); - if(getfulfilledRequirementRes.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); - log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } else { - foundRelation.getSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value()); - } - } - if(result == null){ - result = Either.left(foundRelation); - } - return result; - } - - private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { - return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && - req.getName().equals(relationshipInfo.getRequirement()) && - req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && - req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); - } - - private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { - Either<RequirementCapabilityRelDef, ResponseFormat> result = null; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); - String instanceId = foundRelation.getToNode(); - Optional<CapabilityDefinition> foundCapability; - Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instance.isPresent()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); - log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } - if(result == null){ - for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){ - foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); - if(foundCapability.isPresent()){ - foundRelation.getSingleRelationship().setCapability(foundCapability.get()); - result = Either.left(foundRelation); - } - } - } - if(result == null){ - Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = - toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); - if(getfulfilledRequirementRes.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } else { - foundRelation.getSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); - } - } - if(result == null){ - result = Either.left(foundRelation); - } - return result; - } - - private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { - return cap.getName().equals(relationshipInfo.getCapability()) && - cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && - cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); - } - - private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); - Either<ComponentInstanceProperty, ResponseFormat> result; - if (eitherAttribute.isLeft()) { - log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); - ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); - - result = Either.left(instanceAttribute); - - } else { - log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); - - result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); - - } - return result; - } - - private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - - Either<ComponentInstanceProperty, ResponseFormat> result; - - Wrapper<Integer> indexCounterWrapper = new Wrapper<>(); - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper); - - if (!errorWrapper.isEmpty()) { - result = Either.right(errorWrapper.getInnerElement()); - } else { - Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); - if (eitherAttribute.isLeft()) { - log.debug("Attribute value was added to resource instance {}", resourceInstanceId); - ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); - result = Either.left(instanceAttribute); - - } else { - log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); - result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - } - } - return result; - } - - /** - * Create Or Updates Attribute Instance - * - * @param componentTypeEnum - * @param componentId - * @param resourceInstanceId - * @param attribute - * @param userId - * @return - */ - public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { - Either<ComponentInstanceProperty, ResponseFormat> result = null; - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - - validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); - if (errorWrapper.isEmpty()) { - validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateComponentLock(componentId, componentTypeEnum, errorWrapper); - } - - try { - if (errorWrapper.isEmpty()) { - final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid()); - if (isCreate) { - result = createAttributeValue(attribute, resourceInstanceId); - } else { - result = updateAttributeValue(attribute, resourceInstanceId); - } - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - finally { - if (result == null || result.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - } - - private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { - return StringUtils.isNotEmpty(property.getValue()) - && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) - && ComponentTypeEnum.SERVICE == componentTypeEnum; - } - - private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) { - return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property)); - } - - // US833308 VLI in service - specific network_role property value logic - private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) { - for (ComponentInstanceProperty property: properties) { - if (isNetworkRoleServiceProperty(property, componentTypeEnum)) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreComponentInstances(false); - Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - if (getServiceResult.isRight()) { - return getServiceResult.right().value(); - } - Component service = getServiceResult.left().value(); - Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); - if (!getInstance.isPresent()) { - return StorageOperationStatus.NOT_FOUND; - } - String prefix = service.getSystemName() + "."; - String value = property.getValue(); - if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { - property.setValue(prefix + value); - } - } - } - return StorageOperationStatus.OK; - } - - private Either<String,ResponseFormat> updatePropertyObjectValue(ComponentInstanceProperty property, Map<String, DataTypeDefinition> allDataTypes) { - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); - String newValue = property.getValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, true); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - return Either.left(newValue); - } - - public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) { - - Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on service {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; - } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // specific property value logic US833308 - StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property); - if (StorageOperationStatus.OK != fetchByIdsStatus) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); - - String newValue = property.getValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - - try { - List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId); - Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - instanceProperty.get().setValue(newValue); - if (instanceProperty.isPresent()) { - status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); - } else { - status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); - } - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - List<String> path = new ArrayList<>(); - path.add(foundResourceInstance.getUniqueId()); - property.setPath(path); - - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(property); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) { - - Either<ComponentInstanceInput, ResponseFormat> resultOp = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on service {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; - } - - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); - - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (!res) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } - - try { - List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId); - Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - if (instanceProperty.isPresent()) { - instanceProperty.get().setValue(property.getValue()); - status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); - } else { - status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); - } - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(property); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, - String userId) { - - Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user: {} on service: {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - String propertyValueUid = property.getValueUniqueUid(); - - if (propertyValueUid == null) { - - Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Integer index = counterRes.left().value(); - Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); - - if (result.isLeft()) { - log.trace("Property value was added to resource instance {}", resourceInstanceId); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - - } else { - log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - } - - } else { - Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - - } else { - log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - } - } - if (resultOp.isLeft()) { - StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId); - if (updateCustomizationUUID != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - } - } - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) { - - Either<ComponentInstanceInput, ResponseFormat> resultOp = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user: {} on service: {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - String propertyValueUid = inputProperty.getValueUniqueUid(); - if (propertyValueUid == null) { - - Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Integer index = counterRes.left().value(); - Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true); - - if (result.isLeft()) { - log.debug("Property value was added to resource instance {}", resourceInstanceId); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - - } else { - Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid()); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - } - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user {} on service {}", userId, serviceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", serviceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Property value {} was removed from graph.", propertyValueId); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); - } - - } - - private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { - - Either<Component, ResponseFormat> eitherResponse = null; - ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); - Component component; - ResponseFormat errorResponse; - Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); - if (getComponentRes.isRight()) { - log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); - errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - eitherResponse = Either.right(errorResponse); - } - if (eitherResponse == null) { - component = getComponentRes.left().value(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; - errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); - eitherResponse = Either.right(errorResponse); - } - } - if (eitherResponse == null) { - eitherResponse = Either.left(getComponentRes.left().value()); - } - return eitherResponse; - } - - public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - User user = resp.left().value(); - Either<ComponentInstance, ResponseFormat> resultOp = null; - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); - return resultOp; - } - - ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); - - Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - - try { - - - if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { - resultOp = Either.left(currentResourceInstance); - return resultOp; - - } - String resourceId = newComponentInstance.getComponentUid(); - - - - Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); - if (componentExistsRes.isRight()) { - log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); - return resultOp; - } else if (!componentExistsRes.left().value()) { - log.debug("The resource {} not found ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return resultOp; - } - - Either<Component, ResponseFormat> eitherOriginComponent = getOriginComponentFromComponentInstance(currentResourceInstance, true); - - if (eitherOriginComponent.isRight()) { - resultOp = Either.right(eitherOriginComponent.right().value()); - return resultOp; - } - DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - if (resultOp.isRight()) { - log.debug("failed to delete resource instance {}", resourceId); - return resultOp; - } - ComponentInstance resResourceInfo = resultOp.left().value(); - Component origComponent = null; - OriginTypeEnum originType = currentResourceInstance.getOriginType(); - if (originType == OriginTypeEnum.ServiceProxy) { - Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); - } - origComponent = serviceProxyOrigin.left().value(); - - StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); - - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } - newComponentInstance.setOriginType(originType); - }else{ - - - Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance, true); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - - origComponent = eitherResourceName.left().value(); - - newComponentInstance.setName(resResourceInfo.getName()); - //newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition) origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName()); - } - - newComponentInstance.setInvariantName(resResourceInfo.getInvariantName()); - newComponentInstance.setPosX(resResourceInfo.getPosX()); - newComponentInstance.setPosY(resResourceInfo.getPosY()); - newComponentInstance.setDescription(resResourceInfo.getDescription()); - - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); - - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - - ComponentInstance updatedComponentInstance = resultOp.left().value(); - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - - Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); - if (mergeStatusEither.isRight()) { - return Either.right(mergeStatusEither.right().value()); - } - - /* - * if (CollectionUtils.isNotEmpty(groupInstances)) { StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance( containerComponent, updatedComponentInstance, groupInstances); if - * (addGroupsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError( "ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); - * resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); return resultOp; } - * - * - * } if (MapUtils.isNotEmpty(deploymentArtifacts)) { StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance( containerComponent, updatedComponentInstance, - * deploymentArtifacts); if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError( "ChangeComponentInstanceVersion", - * "Failed to associate groups to new component instance", ErrorSeverity.ERROR); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); return resultOp; } } - */ - - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); - if (updatedComponentRes.isRight()) { - StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", containerComponentId); - return Either.right(responseFormat); - } - resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); - return resultOp; - } - resultOp = Either.left(resourceInstanceStatus.left().value()); - return resultOp; - - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin(); - - protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance(); - - // US831698 - public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { - final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; - Component containerComponent = null; - - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - try { - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); - if (validateUserExists.isRight()) { - resultOp = Either.right(validateUserExists.right().value()); - return resultOp; - } - - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - return resultOp; - } - - Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); - if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - return resultOp; - } - containerComponent = validateContainerComponentExists.left().value(); - - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - return resultOp; - } - - List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); - if (CollectionUtils.isEmpty(instanceProperties)) { - instanceProperties = new ArrayList<>(); - } - resultOp = Either.left(instanceProperties); - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) { - Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); - - if (counterRes.isRight()) { - log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus)); - } else { - instaceCounterWrapper.setInnerElement(counterRes.left().value()); - } - - } - - /** - * updates componentInstance modificationTime - * - * @param componentInstance - * @param componentInstanceType - * @param modificationTime - * @param inTransaction - * @return - */ - public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { - Either<ComponentInstanceData, ResponseFormat> result; - Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, - inTransaction); - if (updateComponentInstanceRes.isRight()) { - log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value()))); - } else { - result = Either.left(updateComponentInstanceRes.left().value()); - } - return result; - } - - public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { - // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; - } - - public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) { - // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; - } - - public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { - // TODO Add implementation - Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); - return result; - } - - private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { - Boolean isUnique = true; - String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName); - if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) { - Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst(); - if (foundComponentInstance.isPresent()) { - isUnique = false; - } - } - return isUnique; - } - - private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) { - - Either<ComponentInstance, StorageOperationStatus> result = null; - List<ComponentInstance> instances = containerComponent.getComponentInstances(); - Optional<ComponentInstance> foundInstance = null; - if (CollectionUtils.isEmpty(instances)) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - if (result == null) { - foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if (!foundInstance.isPresent()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null) { - result = Either.left(foundInstance.get()); - } - return result; - } - - private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { - - Long creationDate = origInstanceForUpdate.getCreationTime(); - - Long modificationTime = System.currentTimeMillis(); - resourceInstanceForUpdate.setCreationTime(creationDate); - resourceInstanceForUpdate.setModificationTime(modificationTime); - - resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) { - resourceInstanceForUpdate.setName(origInstanceForUpdate.getName()); - } - - resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName())); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) - resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) - resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) - resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) - resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); - - if (resourceInstanceForUpdate.getOriginType() == null) { - resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); - } - if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) - resourceInstanceForUpdate.setIsProxy(true); - if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { - resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); - } - if (resourceInstanceForUpdate.getSourceModelName() == null) { - resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName()); - } - if (resourceInstanceForUpdate.getSourceModelUuid() == null) { - resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid()); - } - if (resourceInstanceForUpdate.getSourceModelUid() == null) { - resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); - } - return resourceInstanceForUpdate; - } - /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type - * @param containerComponentType - * @param containerComponentId - * @param componentInstanceUniqueId - * @param capabilityType - * @param capabilityName - * @param userId - * @return - */ - public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String userId) { - - Component containerComponent = null; - - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - try { - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false); - if (validateUserExists.isRight()) { - resultOp = Either.right(validateUserExists.right().value()); - } - if(resultOp == null){ - Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - } - } - if(resultOp == null){ - Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); - if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - } else { - containerComponent = validateContainerComponentExists.left().value(); - } - } - if(resultOp == null){ - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } else { - resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, resourceInstanceStatus.left().value().getCapabilities()); - } - } - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, Map<String, List<CapabilityDefinition>> instanceCapabilities) { - Either<List<ComponentInstanceProperty>, ResponseFormat> result = null; - CapabilityDefinition foundCapability; - if (MapUtils.isNotEmpty(instanceCapabilities)) { - List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType); - if (capabilitiesPerType != null) { - Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName)).findFirst(); - if (capabilityOpt.isPresent()) { - foundCapability = capabilityOpt.get(); - result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); - } - } - } - if (result == null) { - result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName); - } - return result; - } - - private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName) { - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - try { - Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType); - if(getComponentInstanceCapabilityProperties.isRight()){ - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); - } else { - resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); - } - } catch(Exception e){ - log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return resultOp; - } - - private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, - String capabilityType, String capabilityName) { - String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); - StringBuilder sb = new StringBuilder(componentInstanceUniqueId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); - String capKey = sb.toString(); - - Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) - .orElse(Collections.emptyMap()); - List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); - Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny(); - if (cap.isPresent()) { - List<ComponentInstanceProperty> capProperties = cap.get().getProperties(); - if (capProperties != null) { - Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - if (instanceProperty.isPresent()) { - instanceProperty.get().setValue(newValue); - List<String> path = new ArrayList<>(); - path.add(componentInstanceUniqueId); - path.add(capKey); - instanceProperty.get().setPath(path); - status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); - - } - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - } - } - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, - List<ComponentInstanceProperty> properties, String userId) { - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock component {}", containerComponentId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - } - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - - try { - for (ComponentInstanceProperty property : properties) { - Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, allDataTypes.left().value()); - newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), - responseFormat -> Either.right(responseFormat)); - } - Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(properties); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); - } - } + protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) { + + log.debug("add artifacts to resource instance"); + List<GroupDefinition> filteredGroups = null; + ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); + if (!ActionStatus.OK.equals(status)) { + ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); + return Either.right(resultOp); + } + StorageOperationStatus artStatus; + // generate heat_env if necessary + Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); + if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { + + Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(); + Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>(); + + for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { + String type = artifact.getArtifactType(); + if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); + } + if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { + continue; + } + if (artifact.checkEsIdExist()) { + Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + componentInstance.getName(), user, containerComponent, existingEnvVersions); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); + // put env + finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + if (CollectionUtils.isNotEmpty(originComponent.getGroups())) { + filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); + } + if (CollectionUtils.isNotEmpty(filteredGroups)) { + for (GroupDefinition groupInstance : filteredGroups) { + Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + List<ArtifactDefinition> artifactsUid; + if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { + artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); + } else { + artifactsUid = new ArrayList<>(); + } + artifactsUid.add(artifactDefinition); + groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); + break; + } + } + } + } + } + artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); + if (artStatus != StorageOperationStatus.OK) { + log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + + } + StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); + if (result != StorageOperationStatus.OK) { + log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); + } + componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); + } + + artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); + if (artStatus != StorageOperationStatus.OK) { + log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + + } + componentInstance.setArtifacts(originComponent.getArtifacts()); + return Either.left(ActionStatus.OK); + } + + private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); + + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>(); + if (getResourceDeploymentArtifacts.isRight()) { + StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); + if (!status.equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); + return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); + } + } else { + deploymentArtifacts = getResourceDeploymentArtifacts.left().value(); + } + + if (!deploymentArtifacts.isEmpty()) { + Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts); + for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) { + if (!artifact.getValue().checkEsIdExist()) { + tempDeploymentArtifacts.remove(artifact.getKey()); + } + } + + resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts); + } + + return ActionStatus.OK; + } + + public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { + return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); + } + + public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, + boolean needLock, boolean createNewTransaction) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<ComponentInstance, ResponseFormat> resultOp = null; + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + ComponentTypeEnum instanceType = getComponentType(containerComponentType); + Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); + if (validateParentStatus.isRight()) { + log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); + return resultOp; + } + if (!validateParentStatus.left().value()) { + resultOp = Either.right( + componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); + return resultOp; + } + + if (needLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + try { + + Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component origComponent = eitherResourceName.left().value(); + + resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + // New Multiple Instance Update API + public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock, + boolean createNewTransaction) { + + Either<List<ComponentInstance>, ResponseFormat> resultOp = null; + org.openecomp.sdc.be.model.Component containerComponent = null; + try { + Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + ComponentParametersView componentFilter = new ComponentParametersView(); + componentFilter.disableAll(); + componentFilter.setIgnoreUsers(false); + componentFilter.setIgnoreComponentInstances(false); + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + + containerComponent = validateComponentExists.left().value(); + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + ComponentTypeEnum instanceType = getComponentType(containerComponentType); + + for (ComponentInstance componentInstance : componentInstanceList) { + boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); + if (!validateParent) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), + containerComponentId)); + return resultOp; + } + } + + if (needLock) { + + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + + List<ComponentInstance> updatedList = new ArrayList<>(); + List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances(); + List<ComponentInstance> listForUpdate = new ArrayList<>(); + if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) + containerComponent.setComponentInstances(componentInstanceList); + else { + Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator(); + while (iterator.hasNext()) { + ComponentInstance origInst = iterator.next(); + Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); + if (op.isPresent()) { + ComponentInstance updatedCi = op.get(); + updatedCi = buildComponentInstance(updatedCi, origInst); + + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); + return resultOp; + } + + listForUpdate.add(updatedCi); + } else + listForUpdate.add(origInst); + } + containerComponent.setComponentInstances(listForUpdate); + + if (resultOp == null) { + Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); + if (updateStatus.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); + return resultOp; + } + for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { + Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); + if (op.isPresent()) { + updatedList.add(updatedInstance); + } + } + } + } + + resultOp = Either.left(updatedList); + return resultOp; + + } finally { + if (needLock) { + unlockComponent(resultOp, containerComponent); + } + } + } + + private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) { + return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId)); + } + + private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { + if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { + return ComponentTypeEnum.SERVICE_INSTANCE; + } else { + return ComponentTypeEnum.RESOURCE_INSTANCE; + } + } + + private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, + ComponentInstance componentInstance) { + + Either<ComponentInstance, ResponseFormat> resultOp = null; + Optional<ComponentInstance> componentInstanceOptional = null; + Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null; + ComponentInstance oldComponentInstance = null; + boolean isNameChanged = false; + + if (resultOp == null) { + componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); + if (!componentInstanceOptional.isPresent()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + } + } + if (resultOp == null) { + oldComponentInstance = componentInstanceOptional.get(); + String newInstanceName = componentInstance.getName(); + if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) + isNameChanged = true; + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); + } + } + if (resultOp == null) { + updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), + updateRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); + } else { + // region - Update instance Groups + if (isNameChanged) { + Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); + if (result.isRight()) + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); + } + // endregion + } + } + if (resultOp == null) { + String newInstanceId = updateRes.left().value().getRight(); + Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); + + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + } else { + resultOp = Either.left(updatedInstanceOptional.get()); + } + + } + if (resultOp == null) { + resultOp = Either.left(componentInstanceOptional.get()); + } + return resultOp; + } + + /** + * @param oldPrefix- + * The normalized old vf name + * @param newNormailzedPrefix- + * The normalized new vf name + * @param qualifiedGroupInstanceName- + * old Group Instance Name + **/ + // modify group names + private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) { + if (qualifiedGroupInstanceName == null) { + log.info("CANNOT change group name "); + return null; + } + if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) + return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix); + return qualifiedGroupInstanceName; + } + + private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) { + oldComponentInstance.setName(newComponentInstance.getName()); + oldComponentInstance.setModificationTime(System.currentTimeMillis()); + oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); + if (oldComponentInstance.getGroupInstances() != null) + oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); + return oldComponentInstance; + } + + public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + // validate resource + /* + * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils + * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) { + * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } + */ + Either<ComponentInstance, ResponseFormat> resultOp = null; + try { + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); + if (resultOp.isRight()){ + return resultOp; + } + Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, componentInstanceId, + containerComponentType, resultOp); + if (deleteEither.isRight()){ + return deleteEither; + } + return deleteEither; + + } finally { + /* + * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service); + */ + unlockComponent(resultOp, containerComponent); + } + } + + public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, + String componentInstanceId, ComponentTypeEnum containerComponentType, + Either<ComponentInstance, ResponseFormat> resultOp) { + if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){ + + List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstanceId); + if (!pathIDsToBeDeleted.isEmpty()) { + Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId, + pathIDsToBeDeleted); + if(deleteForwardingPathsEither.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + } + return resultOp; + } + + + private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){ + + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if(storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value())); + } + Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(), + Sets.newHashSet(pathIdsToDelete)); + + if(result.isRight()) { + return Either.right(componentsUtils.getResponseFormat(result.right().value())); + } + return Either.left(result.left().value()); + } + + private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){ + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreForwardingPath(false); + Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade + .getToscaElement(containerComponentId, filter); + Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values(); + List<String> pathIDsToBeDeleted = new ArrayList<>(); + + allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId )) + .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId())); + + return pathIDsToBeDeleted; + } + + private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, + String componentInstanceId){ + return pathDataDefinition.getPathElements().getListToscaDataDefinition() + .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || + elementDataDefinition.getToNode() + .equalsIgnoreCase(componentInstanceId)); + } + + + private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { + + Either<ComponentInstance, ResponseFormat> resultOp = null; + ComponentInstance deletedInstance = null; + Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); + + if (deleteRes.isRight()) { + log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } + if (resultOp == null) { + log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); + deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); + resultOp = Either.left(deletedInstance); + } + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { + List<GroupDataDefinition> groupsToUpdate = new ArrayList<>(); + for (GroupDataDefinition currGroup : containerComponent.getGroups()) { + Map<String, String> members = currGroup.getMembers(); + if (members != null && members.containsKey(deletedInstance.getName())) { + members.remove(deletedInstance.getName()); + groupsToUpdate.add(currGroup); + } + } + Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate); + if (updateGroupsRes.isRight()) { + log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } + } + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { + List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(inputsToDelete)) { + StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); + if (deleteInputsRes != StorageOperationStatus.OK) { + log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); + } + } + } + return resultOp; + } + + private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + for (ComponentInstance instance : containerComponent.getComponentInstances()) { + if (instance.getUniqueId().equals(componentInstanceId)) { + foundInstance = instance; + containerComponent.getComponentInstances().remove(instance); + break; + } + } + findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent); + return foundInstance; + } + + private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) { + if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){ + containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList())); + } + } + + private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) { + return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId); + } + + public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true); + } + + public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock, + boolean createNewTransaction) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; + + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + if (needLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); + + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + + try { + + resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); + + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { + + log.debug("Try to create entry on graph"); + Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; + + Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); + + if (result.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); + resultOp = Either.left(requirementCapabilityRelDef); + return resultOp; + + } else { + log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + String fromNameOrId = ""; + String toNameOrId = ""; + Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); + + toNameOrId = requirementDef.getFromNode(); + fromNameOrId = requirementDef.getFromNode(); + if (fromResult.isLeft()) { + fromNameOrId = fromResult.left().value().getName(); + } + if (toResult.isLeft()) { + toNameOrId = toResult.left().value().getName(); + } + + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); + + return resultOp; + } + + } + + public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI"); + + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + try { + log.debug("Try to create entry on graph"); + Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); + if (result.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); + resultOp = Either.left(requirementCapabilityRelDef); + return resultOp; + + } else { + + log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + String fromNameOrId = ""; + String toNameOrId = ""; + Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); + + toNameOrId = requirementDef.getFromNode(); + fromNameOrId = requirementDef.getFromNode(); + if (fromResult.isLeft()) { + fromNameOrId = fromResult.left().value().getName(); + } + if (toResult.isLeft()) { + toNameOrId = toResult.left().value().getName(); + } + + resultOp = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); + return resultOp; + } + } finally { + unlockComponent(resultOp, containerComponent); + } + } + /** + * Allows to get relation contained in specified component according to received Id + * @param componentId + * @param relationId + * @param userId + * @param componentTypeEnum + * @return + */ + public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) { + + Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null; + try { + org.openecomp.sdc.be.model.Component containerComponent = null; + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null; + RequirementCapabilityRelDef foundRelation = null; + + Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false); + if (validateUserRes.isRight()) { + resultOp = Either.right(validateUserRes.right().value()); + } + if(resultOp == null){ + validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + resultOp = Either.right(validateComponentExists.right().value()); + } + } + if(resultOp == null){ + containerComponent = validateComponentExists.left().value(); + List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); + foundRelation = findRelation(relationId, requirementCapabilityRelations); + if(foundRelation == null){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); + log.debug("Relation with id {} was not found on the component", relationId, componentId); + resultOp = Either.right(responseFormat); + } + } + if(resultOp == null){ + resultOp = setRelatedCapability(foundRelation, containerComponent); + } + if(resultOp.isLeft()){ + resultOp = setRelatedRequirement(foundRelation, containerComponent); + } + } catch (Exception e) { + log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) { + for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ + if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){ + return relationship; + } + } + return null; + } + + private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either<RequirementCapabilityRelDef, ResponseFormat> result = null; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + String instanceId = foundRelation.getFromNode(); + Optional<RequirementDefinition> foundRequirement; + Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){ + foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); + if(foundRequirement.isPresent()){ + foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); + log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + return req.getName().equals(relationshipInfo.getRequirement()) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + + private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either<RequirementCapabilityRelDef, ResponseFormat> result = null; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + String instanceId = foundRelation.getToNode(); + Optional<CapabilityDefinition> foundCapability; + Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){ + foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); + if(foundCapability.isPresent()){ + foundRelation.resolveSingleRelationship().setCapability(foundCapability.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = + toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + return cap.getName().equals(relationshipInfo.getCapability()) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + } + + private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); + Either<ComponentInstanceProperty, ResponseFormat> result; + if (eitherAttribute.isLeft()) { + log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); + + result = Either.left(instanceAttribute); + + } else { + log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); + + result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); + + } + return result; + } + + private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + + Either<ComponentInstanceProperty, ResponseFormat> result; + + Wrapper<Integer> indexCounterWrapper = new Wrapper<>(); + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper); + + if (!errorWrapper.isEmpty()) { + result = Either.right(errorWrapper.getInnerElement()); + } else { + Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); + if (eitherAttribute.isLeft()) { + log.debug("Attribute value was added to resource instance {}", resourceInstanceId); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); + result = Either.left(instanceAttribute); + + } else { + log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); + result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + } + } + return result; + } + + /** + * Create Or Updates Attribute Instance + * + * @param componentTypeEnum + * @param componentId + * @param resourceInstanceId + * @param attribute + * @param userId + * @return + */ + public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { + Either<ComponentInstanceProperty, ResponseFormat> result = null; + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + + validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); + if (errorWrapper.isEmpty()) { + validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateComponentLock(componentId, componentTypeEnum, errorWrapper); + } + + try { + if (errorWrapper.isEmpty()) { + final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid()); + if (isCreate) { + result = createAttributeValue(attribute, resourceInstanceId); + } else { + result = updateAttributeValue(attribute, resourceInstanceId); + } + } else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + finally { + if (result == null || result.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { + return StringUtils.isNotEmpty(property.getValue()) + && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) + && ComponentTypeEnum.SERVICE == componentTypeEnum; + } + + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) { + return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property)); + } + + // US833308 VLI in service - specific network_role property value logic + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) { + for (ComponentInstanceProperty property: properties) { + if (isNetworkRoleServiceProperty(property, componentTypeEnum)) { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (getServiceResult.isRight()) { + return getServiceResult.right().value(); + } + Component service = getServiceResult.left().value(); + Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); + if (!getInstance.isPresent()) { + return StorageOperationStatus.NOT_FOUND; + } + String prefix = service.getSystemName() + "."; + String value = property.getValue(); + if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { + property.setValue(prefix + value); + } + } + } + return StorageOperationStatus.OK; + } + + public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) { + + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + + /*-------------------------------Validations---------------------------------*/ + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Properties Values", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // specific property value logic US833308 + StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties); + if (StorageOperationStatus.OK != fetchByIdsStatus) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + + try { + for (ComponentInstanceProperty property: properties) { + Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false); + updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance), + responseFormat -> Either.right(responseFormat)); + } + + Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String capabilityType, String capabilityName) { + String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); + StringBuffer sb = new StringBuffer(componentInstanceUniqueId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); + String capKey = sb.toString(); + + Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) + .orElse(Collections.emptyMap()); + List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST); + Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny(); + if (cap.isPresent()) { + List<ComponentInstanceProperty> capProperties = cap.get().getProperties(); + if (capProperties != null) { + Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(newValue); + List<String> path = new ArrayList<>(); + path.add(componentInstanceUniqueId); + path.add(capKey); + instanceProperty.get().setPath(path); + status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + } + } + } + + + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId()); + Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + instanceProperty.get().setValue(newValue); + if (instanceProperty.isPresent()) { + status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } else { + status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + } + List<String> path = new ArrayList<>(); + path.add(foundResourceInstance.getUniqueId()); + property.setPath(path); + + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) { + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + if (allDataTypesEither.isRight()) { + TitanOperationStatus status = allDataTypesEither.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value(); + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + if (!isInput) { + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } + return Either.left(newValue); + } + + private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId()); + Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(input.getValue()); + status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); + } else { + status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); + } + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) { + + Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + for (ComponentInstanceInput input: inputs) { + Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true); + updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance), + responseFormat -> Either.right(responseFormat)); + + } + Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(inputs); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, + String userId) { + + Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + String propertyValueUid = property.getValueUniqueUid(); + + if (propertyValueUid == null) { + + Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); + + if (counterRes.isRight()) { + log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Integer index = counterRes.left().value(); + Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); + + if (result.isLeft()) { + log.trace("Property value was added to resource instance {}", resourceInstanceId); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + + } else { + log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + } + + } else { + Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + + } else { + log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + } + } + if (resultOp.isLeft()) { + StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId); + if (updateCustomizationUUID != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + } + } + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) { + + Either<ComponentInstanceInput, ResponseFormat> resultOp = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + String propertyValueUid = inputProperty.getValueUniqueUid(); + if (propertyValueUid == null) { + + Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); + + if (counterRes.isRight()) { + log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Integer index = counterRes.left().value(); + Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true); + + if (result.isLeft()) { + log.debug("Property value was added to resource instance {}", resourceInstanceId); + ComponentInstanceInput instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + + } else { + Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid()); + ComponentInstanceInput instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + } + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<ComponentInstanceProperty, ResponseFormat> resultOp = null; + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user {} on service {}", userId, serviceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", serviceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Property value {} was removed from graph.", propertyValueId); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); + } + + } + + private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { + + Either<Component, ResponseFormat> eitherResponse = null; + ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); + Component component; + ResponseFormat errorResponse; + Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); + errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + eitherResponse = Either.right(errorResponse); + } + if (eitherResponse == null) { + component = getComponentRes.left().value(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; + errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); + eitherResponse = Either.right(errorResponse); + } + } + if (eitherResponse == null) { + eitherResponse = Either.left(getComponentRes.left().value()); + } + return eitherResponse; + } + + public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam, + String containerComponentId, + String componentInstanceId, + ComponentInstance newComponentInstance) { + Either<Set<String>, ResponseFormat> resultOp; + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath(); + + //Fetch Component + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = + validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + Component containerComponent = validateComponentExists.left().value(); + + //Fetch current component instance + Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance = + getResourceInstanceById(containerComponent, componentInstanceId); + if (eitherResourceInstance.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); + return resultOp; + } + ComponentInstance currentResourceInstance = eitherResourceInstance.left().value(); + + //Check whether new componentInstance exists + String resourceId = newComponentInstance.getComponentUid(); + Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); + if (componentExistsRes.isRight()) { + log.debug("Failed to find resource ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse + (componentExistsRes.right().value()), resourceId)); + return resultOp; + } else if (!componentExistsRes.left().value()) { + log.debug("The resource {} not found ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + return resultOp; + } + + //Fetch component using new component instance uid + Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component updatedContainerComponent=eitherResourceName.left().value(); + Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent, + currentResourceInstance, updatedContainerComponent); + resultOp=Either.left(toDeleteForwardingPaths); + + return resultOp; + } + + private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance, + Component updatedContainerComponent) { + DataForMergeHolder dataForMergeHolder=new DataForMergeHolder(); + dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId()); + + Service service = (Service) containerComponent; + ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils(); + + return forwardingPathUtils. + getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent); + } + + private ComponentParametersView getComponentParametersViewForForwardingPath() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.setIgnoreCapabiltyProperties(false); + componentParametersView.setIgnoreForwardingPath(false); + return componentParametersView; + } + + public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + User user = resp.left().value(); + Either<ComponentInstance, ResponseFormat> resultOp = null; + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.setIgnoreCapabiltyProperties(false); + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); + return resultOp; + } + + ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); + + Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + + try { + + + if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { + resultOp = Either.left(currentResourceInstance); + return resultOp; + + } + String resourceId = newComponentInstance.getComponentUid(); + + + + Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); + if (componentExistsRes.isRight()) { + log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); + return resultOp; + } else if (!componentExistsRes.left().value()) { + log.debug("The resource {} not found ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + return resultOp; + } + + Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance); + + if (eitherOriginComponent.isRight()) { + resultOp = Either.right(eitherOriginComponent.right().value()); + return resultOp; + } + DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); + if (resultOp.isRight()) { + log.debug("failed to delete resource instance {}", resourceId); + return resultOp; + } + ComponentInstance resResourceInfo = resultOp.left().value(); + Component origComponent = null; + OriginTypeEnum originType = currentResourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); + + StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); + + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); + + } + newComponentInstance.setOriginType(originType); + }else{ + + + Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + + origComponent = eitherResourceName.left().value(); + + newComponentInstance.setName(resResourceInfo.getName()); + } + + newComponentInstance.setInvariantName(resResourceInfo.getInvariantName()); + newComponentInstance.setPosX(resResourceInfo.getPosX()); + newComponentInstance.setPosY(resResourceInfo.getPosY()); + newComponentInstance.setDescription(resResourceInfo.getDescription()); + + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); + + if (resultOp.isRight()) { + log.debug("failed to create resource instance {}", resourceId); + return resultOp; + } + + ComponentInstance updatedComponentInstance = resultOp.left().value(); + if (resultOp.isRight()) { + log.debug("failed to create resource instance {}", resourceId); + return resultOp; + } + + Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); + if (mergeStatusEither.isRight()) { + return Either.right(mergeStatusEither.right().value()); + } + + ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance); + if (postChangeVersionResult != ActionStatus.OK) { + return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult)); + } + + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); + if (updatedComponentRes.isRight()) { + StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("Component with id {} was not found", containerComponentId); + return Either.right(responseFormat); + } + resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); + return resultOp; + } + resultOp = Either.left(resourceInstanceStatus.left().value()); + return resultOp; + + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + // US831698 + public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { + final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; + Component containerComponent = null; + + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + try { + Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + return resultOp; + } + + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + return resultOp; + } + + Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + return resultOp; + } + containerComponent = validateContainerComponentExists.left().value(); + + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + return resultOp; + } + + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); + if (CollectionUtils.isEmpty(instanceProperties)) { + instanceProperties = new ArrayList<>(); + } + resultOp = Either.left(instanceProperties); + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) { + Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); + + if (counterRes.isRight()) { + log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus)); + } else { + instaceCounterWrapper.setInnerElement(counterRes.left().value()); + } + + } + + /** + * updates componentInstance modificationTime + * + * @param componentInstance + * @param componentInstanceType + * @param modificationTime + * @param inTransaction + * @return + */ + public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + Either<ComponentInstanceData, ResponseFormat> result; + Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, + inTransaction); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value()))); + } else { + result = Either.left(updateComponentInstanceRes.left().value()); + } + return result; + } + + public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { + // TODO Add implementation + Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); + return result; + } + + public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) { + // TODO Add implementation + Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); + return result; + } + + public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { + // TODO Add implementation + Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance()); + return result; + } + + private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { + return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent); + } + + private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) { + + Either<ComponentInstance, StorageOperationStatus> result = null; + List<ComponentInstance> instances = containerComponent.getComponentInstances(); + Optional<ComponentInstance> foundInstance = null; + if (CollectionUtils.isEmpty(instances)) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + if (result == null) { + foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if (!foundInstance.isPresent()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null) { + result = Either.left(foundInstance.get()); + } + return result; + } + + private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { + + Long creationDate = origInstanceForUpdate.getCreationTime(); + + Long modificationTime = System.currentTimeMillis(); + resourceInstanceForUpdate.setCreationTime(creationDate); + resourceInstanceForUpdate.setModificationTime(modificationTime); + + resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) { + resourceInstanceForUpdate.setName(origInstanceForUpdate.getName()); + } + + resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName())); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) + resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) + resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) + resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) + resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); + + if (resourceInstanceForUpdate.getOriginType() == null) { + resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); + } + if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) + resourceInstanceForUpdate.setIsProxy(true); + if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { + resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); + } + if (resourceInstanceForUpdate.getSourceModelName() == null) { + resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName()); + } + if (resourceInstanceForUpdate.getSourceModelUuid() == null) { + resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid()); + } + if (resourceInstanceForUpdate.getSourceModelUid() == null) { + resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); + } + return resourceInstanceForUpdate; + } + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + * @param containerComponentType + * @param containerComponentId + * @param componentInstanceUniqueId + * @param capabilityType + * @param capabilityName + * @param userId + * @param ownerId + * @return + */ + public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) { + + Component containerComponent = null; + + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + try { + Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + } + if(resultOp == null){ + Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + } + } + if(resultOp == null){ + Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + } else { + containerComponent = validateContainerComponentExists.left().value(); + } + } + if(resultOp == null){ + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } else { + resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities()); + } + } + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) { + Either<List<ComponentInstanceProperty>, ResponseFormat> result = null; + CapabilityDefinition foundCapability; + if (MapUtils.isNotEmpty(instanceCapabilities)) { + List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType); + if (capabilitiesPerType != null) { + Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst(); + if (capabilityOpt.isPresent()) { + foundCapability = capabilityOpt.get(); + result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); + } + } + } + if (result == null) { + result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId); + } + return result; + } + + private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) { + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + try { + Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); + if(getComponentInstanceCapabilityProperties.isRight()){ + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); + } else { + resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); + } + } catch(Exception e){ + log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String capabilityType, String capabilityName, String ownerId) { + String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); + StringBuilder sb = new StringBuilder(componentInstanceUniqueId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); + String capKey = sb.toString(); + + Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) + .orElse(Collections.emptyMap()); + List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); + Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny(); + if (cap.isPresent()) { + List<ComponentInstanceProperty> capProperties = cap.get().getProperties(); + if (capProperties != null) { + Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(newValue); + List<String> path = new ArrayList<>(); + path.add(componentInstanceUniqueId); + path.add(capKey); + instanceProperty.get().setPath(path); + status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + } + } + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, + List<ComponentInstanceProperty> properties, String userId) { + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock component {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + + try { + for (ComponentInstanceProperty property : properties) { + Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false); + newPropertyValueEither.bimap(updatedValue -> + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId), + responseFormat -> Either.right(responseFormat)); + } + Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); + } + } + + public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, + List<ComponentInstanceProperty> properties, String userId) { + Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock component {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + try { + for (ComponentInstanceProperty property : properties) { + Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false); + newPropertyValueEither.bimap(updatedValue -> + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), + responseFormat -> Either.right(responseFormat)); + } + Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java index f6a108cf75..90f807475f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; @@ -39,7 +31,14 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; /** * This class holds the logic of arranging resource instance on the canvas for imported VF @@ -49,240 +48,240 @@ import fj.data.Either; */ @Component("compositionBusinessLogic") public class CompositionBusinessLogic { - @Autowired - private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic; - - private static final int VFC_CANVAS_ELEMENT_SIZE = 50; - private static final int CP_CANVAS_ELEMENT_SIZE = 21; - private static final int CANVAS_WIDTH = 1000; - private static final int CANVAS_HEIGHT = 700; - private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4; - private static final double CP_RADIUS_FACTOR = 0.4; - - enum RelativePosition { - LEFT, RIGHT, UP, DOWN - }; - - protected Either<List<ComponentInstance>, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) { - Either<List<ComponentInstance>, ResponseFormat> result = Either.left(resource.getComponentInstances()); - - boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null - || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent(); - - if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { - // Arrange Icons In Spiral Pattern - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); - - // Set Relative Locations According to Canvas Size - componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e)); - - // Update in DB - result = vfComponentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false); - - } - return result; - - } - - private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) { - int xCenter = CANVAS_WIDTH / 2; - int yCenter = CANVAS_HEIGHT / 2; - - ImmutablePair<Double, Double> matrixPosition = entry.getKey(); - ComponentInstance componentInstance = entry.getValue(); - componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance)); - componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance)); - } - - private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) { - final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS; - double offsetedCanvasPosition; - switch (componentInstance.getOriginType()) { - case CP: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; - break; - case VL: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; - break; - case VF: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - case VFC: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - case VFCMT: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - default: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - } - return String.valueOf(offsetedCanvasPosition); - } - - protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) { - - Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>(); - - List<ComponentInstance> componentInstances = new ArrayList<>(); - componentInstances.addAll(resource.getComponentInstances()); - Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, resource); - // Remove all cp that are connected from the list - componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList())); - - buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances); - buildCirclePatternForCps(componentInstanceLocations, connectededCps); - - return componentInstanceLocations; - } - - protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) { - - for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) { - Entry<ImmutablePair<Double, Double>, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get(); - buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations); - } - - } - - private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) { - final int numberOfCps = cpsGroup.size(); - double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0; - double currentAngle = 0; - Double xCenter = vfcLocation.getLeft(); - Double yCenter = vfcLocation.getRight(); - for (ComponentInstance currCp : cpsGroup) { - double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle); - double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle); - componentInstLocations.put(new ImmutablePair<Double, Double>(cpXposition, cpYposition), currCp); - currentAngle += angleBetweenCps; - } - - } - - private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) { - int elementsCounter = 0; - ImmutablePair<Double, Double> currPlacement; - ImmutablePair<Double, Double> prevPlacement = null; - RelativePosition relationToPrevElement = null; - for (ComponentInstance curr : componentInstances) { - elementsCounter++; - if (elementsCounter == 1) { - currPlacement = new ImmutablePair<Double, Double>(0D, 0D); - } else if (elementsCounter == 2) { - currPlacement = new ImmutablePair<Double, Double>(-1D, 0D); - relationToPrevElement = RelativePosition.LEFT; - } else { - relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement); - currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement); - - } - - componentInstanceLocations.put(currPlacement, curr); - prevPlacement = currPlacement; - } - } - - protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, Resource vf) { - Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>(); - List<RequirementCapabilityRelDef> allRelations = vf.getComponentInstancesRelations(); - for (ComponentInstance curr : allComponentInstances) { - // Filters Only CPs - if (curr.getOriginType() == OriginTypeEnum.CP) { - // List Of elements the CP is connected to - List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList()); - // Adds Only CPs Which are connected to VFC - filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList); - } - } - return vfcWithItsCps; - } - - private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) { - if (!connectedToTheCPList.isEmpty()) { - // Set Of Ids Of components Instances which are connected certain CP - Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet()); - - // Vfc Component instance Connected to the CP - Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream(). - // All instances connected to CP - filter(p -> mateIds.contains(p.getUniqueId())). - // Filter in only VFC connected to the CP - filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny(); - - if (optionalVfcConnectedToCP.isPresent()) { - final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get(); - if (vfcWithItsCps.containsKey(vfcWithCps)) { - vfcWithItsCps.get(vfcWithCps).add(currCP); - } else { - List<ComponentInstance> cpsList = new ArrayList<>(); - cpsList.add(currCP); - vfcWithItsCps.put(vfcWithCps, cpsList); - } - } - } - } - - private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) { - switch (relationToPrevElement) { - case LEFT: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP; - break; - } - case RIGHT: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN; - break; - } - case UP: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT; - break; - } - case DOWN: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT; - break; - } - default: { - throw new UnsupportedOperationException(); - } - } - return relationToPrevElement; - } - - private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) { - - ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement); - return allElements.containsKey(adjacentElementPosition); - } - - private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) { - ImmutablePair<Double, Double> relativeElementPosition; - switch (relativeLocation) { - - case LEFT: { - relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() - 1, currElement.getRight()); - break; - } - case RIGHT: { - relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() + 1, currElement.getRight()); - break; - } - case UP: { - relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() + 1); - break; - } - case DOWN: { - relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() - 1); - break; - } - default: { - throw new UnsupportedOperationException(); - } - } - return relativeElementPosition; - } + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + private static final int VFC_CANVAS_ELEMENT_SIZE = 50; + private static final int CP_CANVAS_ELEMENT_SIZE = 21; + private static final int CANVAS_WIDTH = 1000; + private static final int CANVAS_HEIGHT = 700; + private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4; + private static final double CP_RADIUS_FACTOR = 0.4; + + enum RelativePosition { + LEFT, RIGHT, UP, DOWN + }; + + protected Either<List<ComponentInstance>, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) { + Either<List<ComponentInstance>, ResponseFormat> result = Either.left(resource.getComponentInstances()); + + boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null + || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent(); + + if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { + // Arrange Icons In Spiral Pattern + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); + + // Set Relative Locations According to Canvas Size + componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e)); + + // Update in DB + result = componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false); + + } + return result; + + } + + private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) { + int xCenter = CANVAS_WIDTH / 2; + int yCenter = CANVAS_HEIGHT / 2; + + ImmutablePair<Double, Double> matrixPosition = entry.getKey(); + ComponentInstance componentInstance = entry.getValue(); + componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance)); + componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance)); + } + + private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) { + final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS; + double offsetedCanvasPosition; + switch (componentInstance.getOriginType()) { + case CP: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; + break; + case VL: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; + break; + case VF: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + case VFC: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + case VFCMT: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + default: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + } + return String.valueOf(offsetedCanvasPosition); + } + + protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) { + + Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>(); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + componentInstances.addAll(resource.getComponentInstances()); + Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, resource); + // Remove all cp that are connected from the list + componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList())); + + buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances); + buildCirclePatternForCps(componentInstanceLocations, connectededCps); + + return componentInstanceLocations; + } + + protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) { + + for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) { + Entry<ImmutablePair<Double, Double>, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get(); + buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations); + } + + } + + private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) { + final int numberOfCps = cpsGroup.size(); + double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0; + double currentAngle = 0; + Double xCenter = vfcLocation.getLeft(); + Double yCenter = vfcLocation.getRight(); + for (ComponentInstance currCp : cpsGroup) { + double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle); + double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle); + componentInstLocations.put(new ImmutablePair<Double, Double>(cpXposition, cpYposition), currCp); + currentAngle += angleBetweenCps; + } + + } + + private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) { + int elementsCounter = 0; + ImmutablePair<Double, Double> currPlacement; + ImmutablePair<Double, Double> prevPlacement = null; + RelativePosition relationToPrevElement = null; + for (ComponentInstance curr : componentInstances) { + elementsCounter++; + if (elementsCounter == 1) { + currPlacement = new ImmutablePair<Double, Double>(0D, 0D); + } else if (elementsCounter == 2) { + currPlacement = new ImmutablePair<Double, Double>(-1D, 0D); + relationToPrevElement = RelativePosition.LEFT; + } else { + relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement); + currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement); + + } + + componentInstanceLocations.put(currPlacement, curr); + prevPlacement = currPlacement; + } + } + + protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, Resource vf) { + Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>(); + List<RequirementCapabilityRelDef> allRelations = vf.getComponentInstancesRelations(); + for (ComponentInstance curr : allComponentInstances) { + // Filters Only CPs + if (curr.getOriginType() == OriginTypeEnum.CP) { + // List Of elements the CP is connected to + List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList()); + // Adds Only CPs Which are connected to VFC + filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList); + } + } + return vfcWithItsCps; + } + + private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) { + if (!connectedToTheCPList.isEmpty()) { + // Set Of Ids Of components Instances which are connected certain CP + Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet()); + + // Vfc Component instance Connected to the CP + Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream(). + // All instances connected to CP + filter(p -> mateIds.contains(p.getUniqueId())). + // Filter in only VFC connected to the CP + filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny(); + + if (optionalVfcConnectedToCP.isPresent()) { + final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get(); + if (vfcWithItsCps.containsKey(vfcWithCps)) { + vfcWithItsCps.get(vfcWithCps).add(currCP); + } else { + List<ComponentInstance> cpsList = new ArrayList<>(); + cpsList.add(currCP); + vfcWithItsCps.put(vfcWithCps, cpsList); + } + } + } + } + + private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) { + switch (relationToPrevElement) { + case LEFT: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP; + break; + } + case RIGHT: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN; + break; + } + case UP: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT; + break; + } + case DOWN: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT; + break; + } + default: { + throw new UnsupportedOperationException(); + } + } + return relationToPrevElement; + } + + private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) { + + ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement); + return allElements.containsKey(adjacentElementPosition); + } + + private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) { + ImmutablePair<Double, Double> relativeElementPosition; + switch (relativeLocation) { + + case LEFT: { + relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() - 1, currElement.getRight()); + break; + } + case RIGHT: { + relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() + 1, currElement.getRight()); + break; + } + case UP: { + relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() + 1); + break; + } + case DOWN: { + relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() - 1); + break; + } + default: { + throw new UnsupportedOperationException(); + } + } + return relativeElementPosition; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java index 9c5cefb24c..44ab4220c8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java @@ -20,8 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Date; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -42,272 +41,271 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.Date; @Component("ConsumerBusinessLogic") public class ConsumerBusinessLogic extends BaseBusinessLogic { - private static final String CONSUMER_NAME = "Consumer name"; - private static final String CONSUMER_SALT = "Consumer salt"; - private static final String CONSUMER_PW = "Consumer password"; - - @javax.annotation.Resource - private IUserBusinessLogic userAdmin; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private ConsumerOperation consumerOperation; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; - - private static Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class.getName()); - - public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) { - - Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - checkFieldsForOverrideAttempt(consumer); - user = userValidation.left().value(); - consumer.setLastModfierAtuid(user.getUserId()); - - Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - if (consumerValidationResponse.isRight()) { - ResponseFormat responseFormat = consumerValidationResponse.right().value(); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - String consumerName = consumer.getConsumerName(); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "createConsumer"); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName); - log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - try { - Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName); - if (getResponse.isLeft() && getResponse.left().value() != null) { - return updateConsumer(consumer, user, true); - } - - Date date = new Date(); - consumer.setConsumerDetailsLastupdatedtime(date.getTime()); - consumer.setConsumerLastAuthenticationTime(Long.valueOf(0)); - - Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer)); - - if (createResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value())); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - log.debug("Consumer created successfully!!!"); - consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } finally { - graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); - } - } - - private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) { - - if (user.getUserId() == null || user.getUserId().trim().isEmpty()) { - log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - log.debug("get user from DB"); - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - - user = eitherCreator.left().value(); - // validate user role - log.debug("validate user role"); - if (!user.getRole().equals(Role.ADMIN.name())) { - log.info("role {} is not allowed to perform this action", user.getRole()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - return Either.left(user); - } - - private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) { - Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer); - if (validateConsumerName.isRight()) { - return Either.right(validateConsumerName.right().value()); - } - Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword = validateConsumerPassword(consumer); - if (validateConsumerPassword.isRight()) { - return Either.right(validateConsumerPassword.right().value()); - } - consumer = validateConsumerPassword.left().value(); - Either<ConsumerDefinition, ResponseFormat> validateEcompUserSalt = validateConsumerSalt(consumer); - if (validateEcompUserSalt.isRight()) { - return Either.right(validateEcompUserSalt.right().value()); - } - return Either.left(consumer); - - } - - private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) { - String name = consumer.getConsumerName(); - if (!ValidationUtils.validateStringNotEmpty(name)) { - log.debug("Consumer name cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME)); - } - if (!ValidationUtils.validateConsumerName(name)) { - log.debug("Consumer name is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); - } - if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) { - log.debug("Consumer name exceeds limit."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH))); - } - if (!ValidationUtils.isUTF8Str(name)) { - log.debug("Consumer name includes non UTF 8 characters."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); - } - - return Either.left(consumer); - } - - private Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword(ConsumerDefinition consumer) { - String password = consumer.getConsumerPassword(); - if (!ValidationUtils.validateStringNotEmpty(password)) { - log.debug("Consumer password cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW)); - } - if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) { - log.debug("Consumer password length is not valid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW)); - } - consumer.setConsumerPassword(password.toLowerCase()); - if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) { - log.debug("Consumer password is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW)); - } - - return Either.left(consumer); - } - - private Either<ConsumerDefinition, ResponseFormat> validateConsumerSalt(ConsumerDefinition consumer) { - String salt = consumer.getConsumerSalt(); - if (!ValidationUtils.validateStringNotEmpty(salt)) { - log.debug("Consumer salt cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT)); - } - if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) { - log.debug("Consumer salt length is not valid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT)); - } - if (!ValidationUtils.validateConsumerPassSalt(salt)) { - log.debug("Consumer salt is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT)); - } - - return Either.left(consumer); - } - - public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId, User user) { - ConsumerDefinition tmpConsumer = new ConsumerDefinition(); - tmpConsumer.setConsumerName(consumerId); - // In case of filter (southbound) call - if (user != null) { - Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - user = userValidation.left().value(); - } - Either<ConsumerData, StorageOperationStatus> getResult = consumerOperation.getCredentials(consumerId); - if (getResult.isRight()) { - ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value()); - ResponseFormat responseFormat; - if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(action, consumerId); - } else { - responseFormat = componentsUtils.getResponseFormat(action); - } - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); - return Either.right(responseFormat); - } - ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } - - public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId) { - return getConsumer(consumerId, null); - } - - public Either<ConsumerDefinition, ResponseFormat> deleteConsumer(String consumerId, User user) { - ConsumerDefinition tmpConsumer = new ConsumerDefinition(); - tmpConsumer.setConsumerName(consumerId); - Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - user = userValidation.left().value(); - Either<ConsumerData, StorageOperationStatus> deleteResult = consumerOperation.deleteCredentials(consumerId); - if (deleteResult.isRight()) { - ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value()); - ResponseFormat responseFormat; - if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(action, consumerId); - } else { - responseFormat = componentsUtils.getResponseFormat(action); - } - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); - return Either.right(responseFormat); - } - ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } - - public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) { - Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer)); - if (updateResult.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); - return Either.right(responseFormat); - } - consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition()); - return Either.left(consumer); - } - - private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) { - if (consumer.getConsumerDetailsLastupdatedtime() != null) { - log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application"); - } - if (consumer.getConsumerLastAuthenticationTime() != null) { - log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application"); - } - if (consumer.getLastModfierAtuid() != null) { - log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application"); - } - } + private static final String CONSUMER_NAME = "Consumer name"; + private static final String CONSUMER_SALT = "Consumer salt"; + private static final String CONSUMER_PW = "Consumer password"; + + @javax.annotation.Resource + private IUserBusinessLogic userAdmin; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private ConsumerOperation consumerOperation; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + private static final Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class); + + public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) { + + Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + checkFieldsForOverrideAttempt(consumer); + user = userValidation.left().value(); + consumer.setLastModfierAtuid(user.getUserId()); + + Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + if (consumerValidationResponse.isRight()) { + ResponseFormat responseFormat = consumerValidationResponse.right().value(); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + String consumerName = consumer.getConsumerName(); + StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName); + log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + try { + Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName); + if (getResponse.isLeft() && getResponse.left().value() != null) { + return updateConsumer(consumer, user, true); + } + + Date date = new Date(); + consumer.setConsumerDetailsLastupdatedtime(date.getTime()); + consumer.setConsumerLastAuthenticationTime(Long.valueOf(0)); + + Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer)); + + if (createResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value())); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + log.debug("Consumer created successfully!!!"); + consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } finally { + graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); + } + } + + private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) { + + if (user.getUserId() == null || user.getUserId().trim().isEmpty()) { + log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + log.debug("get user from DB"); + Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + + user = eitherCreator.left().value(); + // validate user role + log.debug("validate user role"); + if (!user.getRole().equals(Role.ADMIN.name())) { + log.info("role {} is not allowed to perform this action", user.getRole()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + return Either.left(user); + } + + private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) { + Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer); + if (validateConsumerName.isRight()) { + return Either.right(validateConsumerName.right().value()); + } + Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword = validateConsumerPassword(consumer); + if (validateConsumerPassword.isRight()) { + return Either.right(validateConsumerPassword.right().value()); + } + consumer = validateConsumerPassword.left().value(); + Either<ConsumerDefinition, ResponseFormat> validateEcompUserSalt = validateConsumerSalt(consumer); + if (validateEcompUserSalt.isRight()) { + return Either.right(validateEcompUserSalt.right().value()); + } + return Either.left(consumer); + + } + + private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) { + String name = consumer.getConsumerName(); + if (!ValidationUtils.validateStringNotEmpty(name)) { + log.debug("Consumer name cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME)); + } + if (!ValidationUtils.validateConsumerName(name)) { + log.debug("Consumer name is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); + } + if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) { + log.debug("Consumer name exceeds limit."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH))); + } + if (!ValidationUtils.isUTF8Str(name)) { + log.debug("Consumer name includes non UTF 8 characters."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); + } + + return Either.left(consumer); + } + + private Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword(ConsumerDefinition consumer) { + String password = consumer.getConsumerPassword(); + if (!ValidationUtils.validateStringNotEmpty(password)) { + log.debug("Consumer password cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW)); + } + if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) { + log.debug("Consumer password length is not valid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW)); + } + consumer.setConsumerPassword(password.toLowerCase()); + if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) { + log.debug("Consumer password is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW)); + } + + return Either.left(consumer); + } + + private Either<ConsumerDefinition, ResponseFormat> validateConsumerSalt(ConsumerDefinition consumer) { + String salt = consumer.getConsumerSalt(); + if (!ValidationUtils.validateStringNotEmpty(salt)) { + log.debug("Consumer salt cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT)); + } + if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) { + log.debug("Consumer salt length is not valid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT)); + } + if (!ValidationUtils.validateConsumerPassSalt(salt)) { + log.debug("Consumer salt is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT)); + } + + return Either.left(consumer); + } + + public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId, User user) { + ConsumerDefinition tmpConsumer = new ConsumerDefinition(); + tmpConsumer.setConsumerName(consumerId); + // In case of filter (southbound) call + if (user != null) { + Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + user = userValidation.left().value(); + } + Either<ConsumerData, StorageOperationStatus> getResult = consumerOperation.getCredentials(consumerId); + if (getResult.isRight()) { + ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value()); + ResponseFormat responseFormat; + if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(action, consumerId); + } else { + responseFormat = componentsUtils.getResponseFormat(action); + } + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); + return Either.right(responseFormat); + } + ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } + + public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId) { + return getConsumer(consumerId, null); + } + + public Either<ConsumerDefinition, ResponseFormat> deleteConsumer(String consumerId, User user) { + ConsumerDefinition tmpConsumer = new ConsumerDefinition(); + tmpConsumer.setConsumerName(consumerId); + Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + user = userValidation.left().value(); + Either<ConsumerData, StorageOperationStatus> deleteResult = consumerOperation.deleteCredentials(consumerId); + if (deleteResult.isRight()) { + ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value()); + ResponseFormat responseFormat; + if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(action, consumerId); + } else { + responseFormat = componentsUtils.getResponseFormat(action); + } + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); + return Either.right(responseFormat); + } + ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } + + public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) { + Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer)); + if (updateResult.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); + return Either.right(responseFormat); + } + consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition()); + return Either.left(consumer); + } + + private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) { + if (consumer.getConsumerDetailsLastupdatedtime() != null) { + log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application"); + } + if (consumer.getConsumerLastAuthenticationTime() != null) { + log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application"); + } + if (consumer.getLastModfierAtuid() != null) { + log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application"); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index 53dceb8112..6fbc22454d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -20,19 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -44,35 +32,40 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; public class CsarValidationUtils { - private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName()); + private static final Logger log = LoggerFactory.getLogger(CsarValidationUtils.class); - private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; + private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; - private static final String CSAR_VERSION = "CSAR-Version"; + private static final String CSAR_VERSION = "CSAR-Version"; - private static final String CREATED_BY = "Created-By"; + private static final String CREATED_BY = "Created-By"; - private static final String NEW_LINE_DELM = "\n"; + private static final String NEW_LINE_DELM = "\n"; - //public final static String TOSCA_METADATA_FILE = "TOSCA-Metadata/TOSCA.meta"; - public final static String TOSCA_METADATA = "TOSCA-Metadata"; - public final static String TOSCA_FILE = "TOSCA.meta"; - public final static String DEL_PATTERN = "([/\\\\]+)"; - public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA + - // Artifact Group (i.e Deployment/Informational) - DEL_PATTERN + TOSCA_FILE; + public final static String TOSCA_METADATA = "TOSCA-Metadata"; + public final static String TOSCA_FILE = "TOSCA.meta"; + public final static String DEL_PATTERN = "([/\\\\]+)"; + public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA + + // Artifact Group (i.e Deployment/Informational) + DEL_PATTERN + TOSCA_FILE; - public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; + public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; - private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; + private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; - public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta"; + public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta"; - public static final String TOSCA_CSAR_EXTENSION = ".csar"; + public static final String TOSCA_CSAR_EXTENSION = ".csar"; /** * Validates Csar * @param csar @@ -80,275 +73,269 @@ public class CsarValidationUtils { * @param componentsUtils * @return */ - public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - - removeNonUniqueArtifactsFromCsar(csar); - - log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID); - validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - return Either.left(true); - } - - private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) { - - List<String> nonUniqueArtifactsToRemove = new ArrayList<>(); - String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]); - int numberOfArtifacts = paths.length; - for(int i = 0; i < numberOfArtifacts; ++i ){ - collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); - } - nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path)); - } - - private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) { - - String[] parsedPath = paths[currInd].split("/"); - String[] otherParsedPath; - int artifactNameInd = parsedPath.length - 1; - for(int j = currInd + 1; j < numberOfArtifacts; ++j ){ - otherParsedPath = paths[j].split("/"); - if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){ - log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ", - parsedPath[artifactNameInd], paths[currInd], paths[j]); - nonUniqueArtifactsToRemove.add(paths[j]); - } - } - } - - private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) { - boolean isEqualArtifactNames = false; - int artifactNameInd = parsedPath.length - 1; - int artifactGroupTypeInd = parsedPath.length - 3; - String groupType = parsedPath[artifactGroupTypeInd]; - String artifactName = parsedPath[artifactNameInd]; - String otherGroupType = otherParsedPath[artifactGroupTypeInd]; - String otherArtifactName = otherParsedPath[artifactNameInd]; - String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; - - if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ - isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); - } - return isEqualArtifactNames; - } - - public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - byte[] toscaMetaBytes = csar.get(keyOp.get()); - Properties props = new Properties(); - try { - //props.load(new ByteArrayInputStream(toscaMetaBytes)); - String propStr = new String(toscaMetaBytes); - props.load(new StringReader(propStr.replace("\\","\\\\"))); - } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS); - String[] ops = yamlFileName.split(DEL_PATTERN); - List<String> list = Arrays.asList(ops); - String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN)); - keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); - } - - log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID); - byte[] yamlFileBytes = csar.get(yamlFileName); - if (yamlFileBytes == null) { - log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); - } - - String yamlFileContents = new String(yamlFileBytes); - - return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents)); - } - - public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - - if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) { - log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE)); - } - - log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID); - byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE); - if (artifactsMetaBytes == null) { - log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)); - } - - String artifactsFileContents = new String(artifactsMetaBytes); - - return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); - } - - public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { - if (!csar.containsKey(artifactPath)) { - log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); - } - - log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID); - byte[] artifactFileBytes = csar.get(artifactPath); - if (artifactFileBytes == null) { - log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID)); - } - - return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes)); - } - - private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - byte[] toscaMetaBytes = csar.get(keyOp.get()); - String toscaMetadata = new String(toscaMetaBytes); - String[] splited = toscaMetadata.split(NEW_LINE_DELM); - if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - /* - * if(splited.length == TOSCA_METADATA_FIELDS.length){ if(!toscaMetadata.endsWith(NEW_LINE_DELM)){ log. debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}" , csarUUID); - * BeEcompErrorManager.getInstance(). logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " +csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return - * Either.right(componentsUtils.getResponseFormat(ActionStatus. CSAR_INVALID_FORMAT, csarUUID)); } } - */ - - Either<Boolean, ResponseFormat> block_0Status = validateBlock_0(csarUUID, splited, componentsUtils); - if (block_0Status.isRight()) { - return Either.right(block_0Status.right().value()); - } - - return Either.left(true); - - } - - private static Either<Boolean, ResponseFormat> validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) { - int index = 0; - for (String toscaField : TOSCA_METADATA_FIELDS) { - - Properties props = new Properties(); - - try { - props.load(new ByteArrayInputStream(splited[index].getBytes())); - } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - if (!props.containsKey(toscaField)) { - log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - String value = props.getProperty(toscaField); - if (value == null || value.isEmpty()) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format - // validation - if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) { - if (!validateTOSCAMetaProperty(value)) { - log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - } - index++; - } - return Either.left(true); - } - - private static boolean validateTOSCAMetaProperty(String toscaProperty) { - final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$"; - final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING); - - Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty); - return floatMatcher.matches(); - } - - private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - if (csar == null || csar.isEmpty()) { - log.debug("Error when fetching csar with ID {}", csarUUID); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID); - return Either.right(responseFormat); - } - - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - - log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - byte[] toscaMetaBytes = csar.get(keyOp.get()); - // && exchanged for || - if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { - log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - - return Either.left(Boolean.TRUE); - } - - public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { - - Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils); - if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) { - log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID); - return Either.right(toscaYamlRes.right().value()); - } - - String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes()); - return Either.left(newCheckSum); - - } - - public static boolean isCsarPayloadName(String payloadName) { - if (payloadName == null) - return false; - return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION); - } + public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + + removeNonUniqueArtifactsFromCsar(csar); + + log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID); + validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + return Either.left(true); + } + + private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) { + + List<String> nonUniqueArtifactsToRemove = new ArrayList<>(); + String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]); + int numberOfArtifacts = paths.length; + for(int i = 0; i < numberOfArtifacts; ++i ){ + collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); + } + nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path)); + } + + private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) { + + String[] parsedPath = paths[currInd].split("/"); + String[] otherParsedPath; + int artifactNameInd = parsedPath.length - 1; + for(int j = currInd + 1; j < numberOfArtifacts; ++j ){ + otherParsedPath = paths[j].split("/"); + if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){ + log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ", + parsedPath[artifactNameInd], paths[currInd], paths[j]); + nonUniqueArtifactsToRemove.add(paths[j]); + } + } + } + + private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) { + boolean isEqualArtifactNames = false; + int artifactNameInd = parsedPath.length - 1; + int artifactGroupTypeInd = parsedPath.length - 3; + String groupType = parsedPath[artifactGroupTypeInd]; + String artifactName = parsedPath[artifactNameInd]; + String otherGroupType = otherParsedPath[artifactGroupTypeInd]; + String otherArtifactName = otherParsedPath[artifactNameInd]; + String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; + + if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ + isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); + } + return isEqualArtifactNames; + } + + public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + byte[] toscaMetaBytes = csar.get(keyOp.get()); + Properties props = new Properties(); + try { + String propStr = new String(toscaMetaBytes); + props.load(new StringReader(propStr.replace("\\","\\\\"))); + } catch (IOException e) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS); + String[] ops = yamlFileName.split(DEL_PATTERN); + List<String> list = Arrays.asList(ops); + String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN)); + keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); + } + + log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID); + byte[] yamlFileBytes = csar.get(yamlFileName); + if (yamlFileBytes == null) { + log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); + } + + String yamlFileContents = new String(yamlFileBytes); + + return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents)); + } + + public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + + if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) { + log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE)); + } + + log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID); + byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE); + if (artifactsMetaBytes == null) { + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)); + } + + String artifactsFileContents = new String(artifactsMetaBytes); + + return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); + } + + public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { + if (!csar.containsKey(artifactPath)) { + log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); + } + + log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID); + byte[] artifactFileBytes = csar.get(artifactPath); + if (artifactFileBytes == null) { + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID)); + } + + return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes)); + } + + private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + byte[] toscaMetaBytes = csar.get(keyOp.get()); + String toscaMetadata = new String(toscaMetaBytes); + String[] splited = toscaMetadata.split(NEW_LINE_DELM); + if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + Either<Boolean, ResponseFormat> block_0Status = validateBlock_0(csarUUID, splited, componentsUtils); + if (block_0Status.isRight()) { + return Either.right(block_0Status.right().value()); + } + + return Either.left(true); + + } + + private static Either<Boolean, ResponseFormat> validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) { + int index = 0; + for (String toscaField : TOSCA_METADATA_FIELDS) { + + Properties props = new Properties(); + + try { + props.load(new ByteArrayInputStream(splited[index].getBytes())); + } catch (IOException e) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + if (!props.containsKey(toscaField)) { + log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + String value = props.getProperty(toscaField); + if (value == null || value.isEmpty()) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format + // validation + if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) { + if (!validateTOSCAMetaProperty(value)) { + log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + } + index++; + } + return Either.left(true); + } + + private static boolean validateTOSCAMetaProperty(String toscaProperty) { + final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$"; + final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING); + + Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty); + return floatMatcher.matches(); + } + + private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + if (csar == null || csar.isEmpty()) { + log.debug("Error when fetching csar with ID {}", csarUUID); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID); + return Either.right(responseFormat); + } + + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + + log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + byte[] toscaMetaBytes = csar.get(keyOp.get()); + // && exchanged for || + if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { + log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + + return Either.left(Boolean.TRUE); + } + + public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) { + + Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils); + if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) { + log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID); + return Either.right(toscaYamlRes.right().value()); + } + + String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes()); + return Either.left(newCheckSum); + + } + + public static boolean isCsarPayloadName(String payloadName) { + if (payloadName == null) + return false; + return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java index e5fba0dff5..aa5cb4e2ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -45,211 +36,214 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; @Component("dataTypeImportManager") public class DataTypeImportManager { - public static void main(String[] args) { - - List<PropertyDefinition> properties = new ArrayList<>(); - PropertyDefinition propertyDefintion = new PropertyDefinition(); - propertyDefintion.setName("aaa"); - properties.add(propertyDefintion); - - List<String> allParentsProps = new ArrayList<>(); - allParentsProps.add("aaa"); - allParentsProps.add("bbb"); - - Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - System.out.println(alreadyExistPropsCollection); - - } - - private static Logger log = LoggerFactory.getLogger(DataTypeImportManager.class.getName()); - @Resource - private PropertyOperation propertyOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) { - return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType); - } - - private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) { - - return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData)); - - } - - private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) { - - return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()), - dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType)); - } - - private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) { - - String dataTypeName = dataType.getName(); - List<PropertyDefinition> properties = dataType.getProperties(); - if (properties == null) { - // At least one parameter should be defined either in the properties - // section or at one of the parents - String derivedDataType = dataType.getDerivedFromName(); - // If there are no properties, then we can create a data type if it - // is an abstract one or it derives from non abstract data type - if ((derivedDataType == null || derivedDataType.isEmpty())) { - if (false == isAbstract(dataType.getName())) { - if (false == ToscaPropertyType.isScalarType(dataTypeName)) { - log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); - - return Either.right(responseFormat); - } - } - } else { - // if it is not a scalar data type and it derives from abstract - // data type, we should reject the request. - if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) { - log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); - - return Either.right(responseFormat); - } - } - } else { - // properties tag cannot be empty - if (properties.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null); - - return Either.right(responseFormat); - } - - // check no duplicates - Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet()); - if (collect != null) { - if (properties.size() != collect.size()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null); - - return Either.right(responseFormat); - } - } - - List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList()); - if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) { - log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType); - - return Either.right(responseFormat); - } - } - - String derivedDataType = dataType.getDerivedFromName(); - if (derivedDataType != null) { - Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true); - if (derivedDataTypeByName.isRight()) { - StorageOperationStatus status = derivedDataTypeByName.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null); - - return Either.right(responseFormat); - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null); - - return Either.right(responseFormat); - - } - } else { - - DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value(); - if (properties != null && properties.isEmpty() == false) { - - if (true == isScalarType(derivedDataTypeDef)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null); - - return Either.right(responseFormat); - } - - Set<String> allParentsProps = new HashSet<>(); - do { - List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties(); - if (currentParentsProps != null) { - for (PropertyDefinition propertyDefinition : currentParentsProps) { - allParentsProps.add(propertyDefinition.getName()); - } - } - derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom(); - } while (derivedDataTypeDef != null); - - // Check that no property is already defined in one of the - // ancestors - Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) { - List<String> duplicateProps = new ArrayList<>(); - duplicateProps.addAll(alreadyExistPropsCollection); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); - - return Either.right(responseFormat); - } - - } - } - } - return Either.left(ActionStatus.OK); - } - - private boolean isAbstract(String dataTypeName) { - - ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); - - return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true; - - } - - private boolean isScalarType(DataTypeDefinition dataTypeDef) { - - boolean isScalar = false; - DataTypeDefinition dataType = dataTypeDef; - - while (dataType != null) { - - String name = dataType.getName(); - if (ToscaPropertyType.isScalarType(name)) { - isScalar = true; - break; - } + public static void main(String[] args) { + + List<PropertyDefinition> properties = new ArrayList<>(); + PropertyDefinition propertyDefintion = new PropertyDefinition(); + propertyDefintion.setName("aaa"); + properties.add(propertyDefintion); + + List<String> allParentsProps = new ArrayList<>(); + allParentsProps.add("aaa"); + allParentsProps.add("bbb"); + + Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + System.out.println(alreadyExistPropsCollection); + + } + + private static final Logger log = LoggerFactory.getLogger(DataTypeImportManager.class); + @Resource + private PropertyOperation propertyOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) { + return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType); + } + + private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) { + + return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData)); + + } + + private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) { + + return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()), + dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType)); + } + + private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) { + + String dataTypeName = dataType.getName(); + List<PropertyDefinition> properties = dataType.getProperties(); + if (properties == null) { + // At least one parameter should be defined either in the properties + // section or at one of the parents + String derivedDataType = dataType.getDerivedFromName(); + // If there are no properties, then we can create a data type if it + // is an abstract one or it derives from non abstract data type + if (derivedDataType == null || derivedDataType.isEmpty()) { + if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) { + log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); + return Either.right(responseFormat); + } + } else { + // if it is not a scalar data type and it derives from abstract + // data type, we should reject the request. + if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) { + log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); + return Either.right(responseFormat); + } + } + } else { + // properties tag cannot be empty + if (properties.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null); + + return Either.right(responseFormat); + } + + // check no duplicates + Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet()); + if (collect != null) { + if (properties.size() != collect.size()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null); + + return Either.right(responseFormat); + } + } + + List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList()); + if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) { + log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType); + + return Either.right(responseFormat); + } + } + + String derivedDataType = dataType.getDerivedFromName(); + if (derivedDataType != null) { + Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true); + if (derivedDataTypeByName.isRight()) { + StorageOperationStatus status = derivedDataTypeByName.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null); + + return Either.right(responseFormat); + } else { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null); + + return Either.right(responseFormat); + + } + } else { + + DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value(); + if (properties != null && properties.isEmpty() == false) { + + if (true == isScalarType(derivedDataTypeDef)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null); + + return Either.right(responseFormat); + } + + Set<String> allParentsProps = new HashSet<>(); + do { + List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties(); + if (currentParentsProps != null) { + for (PropertyDefinition propertyDefinition : currentParentsProps) { + allParentsProps.add(propertyDefinition.getName()); + } + } + derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom(); + } while (derivedDataTypeDef != null); + + // Check that no property is already defined in one of the + // ancestors + Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) { + List<String> duplicateProps = new ArrayList<>(); + duplicateProps.addAll(alreadyExistPropsCollection); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); + + return Either.right(responseFormat); + } + + } + } + } + return Either.left(ActionStatus.OK); + } + + private boolean isAbstract(String dataTypeName) { + + ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); + + return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true; + + } + + private boolean isScalarType(DataTypeDefinition dataTypeDef) { + + boolean isScalar = false; + DataTypeDefinition dataType = dataTypeDef; + + while (dataType != null) { + + String name = dataType.getName(); + if (ToscaPropertyType.isScalarType(name)) { + isScalar = true; + break; + } - dataType = dataType.getDerivedFrom(); - } + dataType = dataType.getDerivedFrom(); + } - return isScalar; - } + return isScalar; + } - private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) { - DataTypeDefinition dataType = new DataTypeDefinition(); + private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) { + DataTypeDefinition dataType = new DataTypeDefinition(); - dataType.setName(dataTypeName); + dataType.setName(dataTypeName); - if (toscaJson != null) { - // Description - final Consumer<String> descriptionSetter = description -> dataType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer<String> derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values)); + if (toscaJson != null) { + // Description + final Consumer<String> descriptionSetter = description -> dataType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer<String> derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values)); - setConstraints(toscaJson, dataType); - } - return dataType; - } + setConstraints(toscaJson, dataType); + } + return dataType; + } - private void setConstraints(Map<String, Object> toscaJson, DataTypeDefinition dataType) { - // TODO Auto-generated method stub + private void setConstraints(Map<String, Object> toscaJson, DataTypeDefinition dataType) { + // TODO Auto-generated method stub - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java index be3ac13cc9..5469d79653 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -46,172 +41,170 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; @Component("distributionMonitoringBusinessLogic") public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { - private static final String DEPLOYED = "Deployed"; - - private static final String ERROR = "Error"; - - private static final String DISTRIBUTED = "Distributed"; - - private static final String IN_PROGRESS = "In Progress"; - - private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); - - // @javax.annotation.Resource - // private AuditingDao auditingDao; - - @Autowired - private AuditCassandraDao cassandraDao; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - public DistributionMonitoringBusinessLogic() { - } - - public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Status", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.trace("getListOfDistributionStatus for did {}", did); - Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); - if (distributionStatus.isRight()) { - log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value()); - return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did)); - } - List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<DistributionStatusInfo>(); - List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value(); - if (distributionStatusEventList != null) { - for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) { - distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); - } - } - - DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse(); - distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList); - log.trace("list statuses for did {} is {} ", did, distribStatusInfoList); - return Either.left(distributionStatusListResponse); - } - - public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Service Status", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); - Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); - if (status.isRight()) { - log.debug("failed to find service distribution statuses. error: {}", status); - return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid)); - } - List<DistributionStatusOfServiceInfo> distribStatusInfoList = new ArrayList<DistributionStatusOfServiceInfo>(); - List<? extends AuditingGenericEvent> distributionStatusEventList = status.left().value(); - distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList); - DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce(); - distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList); - return Either.left(distributionStatusListResponse); - } - - private List<DistributionStatusOfServiceInfo> handleAuditingDaoResponse(List<? extends AuditingGenericEvent> distribStatusInfoList) { - List<DistributionStatusOfServiceInfo> reslist = new ArrayList<DistributionStatusOfServiceInfo>(); - Map<String, List<AuditingGenericEvent>> serviceDidMap = createServiceDidMap(distribStatusInfoList); - Set<String> didSet = serviceDidMap.keySet(); - for (String did : didSet) { - DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo(); - distributionStatusOfServiceInfo.setDistributionID(did); - String dReguestStatus = ""; - String dNotifyStatus = ""; - boolean isResult = false; - List<? extends AuditingGenericEvent> auditingGenericEventList = serviceDidMap.get(did); - ESTimeBasedEvent resAuditingGenericEvent = null; - for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { - auditingGenericEvent.fillFields(); - - String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName()); - Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName()); - if (modifierUserId != null) { - distributionStatusOfServiceInfo.setUserId((String) modifierUserId); - } - - if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) { - - isResult = true; - resAuditingGenericEvent = auditingGenericEvent; - break; - } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) { - dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent); - } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) { - dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent); - } - - resAuditingGenericEvent = auditingGenericEvent; - - } - distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName())); - - if (!isResult) { - if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) { - if (dNotifyStatus.isEmpty()) { - distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS); - - } else { - if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) - distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED); - else - distributionStatusOfServiceInfo.setDeployementStatus(ERROR); - } - } else - distributionStatusOfServiceInfo.setDeployementStatus(ERROR); - } else - distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED); - reslist.add(distributionStatusOfServiceInfo); - } - - return reslist; - } - - private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) { - String status = ""; - Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName()); - if (requestStatus instanceof String) { - status = (String) requestStatus; - } - return status; - } - - private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) { - - Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<String, List<AuditingGenericEvent>>(); - for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) { - List<AuditingGenericEvent> auditingGenericEventList = null; - String did = ""; - auditingGenericEvent.fillFields(); - - Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName()); - if (didValue != null) { - did = (String) didValue; - } - - if (!did.isEmpty()) { - if (serviceDidMap.containsKey(did)) { - auditingGenericEventList = serviceDidMap.get(did); - } - if (auditingGenericEventList == null) { - auditingGenericEventList = new ArrayList(); - - } - auditingGenericEventList.add(auditingGenericEvent); - serviceDidMap.put(did, auditingGenericEventList); - } - } - return serviceDidMap; - } + private static final String DEPLOYED = "Deployed"; + + private static final String ERROR = "Error"; + + private static final String DISTRIBUTED = "Distributed"; + + private static final String IN_PROGRESS = "In Progress"; + + private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class); + + + @Autowired + private AuditCassandraDao cassandraDao; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + public DistributionMonitoringBusinessLogic() { + } + + public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Status", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.trace("getListOfDistributionStatus for did {}", did); + Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); + if (distributionStatus.isRight()) { + log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value()); + return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did)); + } + List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<DistributionStatusInfo>(); + List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value(); + if (distributionStatusEventList != null) { + for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) { + distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); + } + } + + DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse(); + distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList); + log.trace("list statuses for did {} is {} ", did, distribStatusInfoList); + return Either.left(distributionStatusListResponse); + } + + public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Service Status", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); + Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); + if (status.isRight()) { + log.debug("failed to find service distribution statuses. error: {}", status); + return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid)); + } + List<DistributionStatusOfServiceInfo> distribStatusInfoList = new ArrayList<DistributionStatusOfServiceInfo>(); + List<? extends AuditingGenericEvent> distributionStatusEventList = status.left().value(); + distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList); + DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce(); + distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList); + return Either.left(distributionStatusListResponse); + } + + private List<DistributionStatusOfServiceInfo> handleAuditingDaoResponse(List<? extends AuditingGenericEvent> distribStatusInfoList) { + List<DistributionStatusOfServiceInfo> reslist = new ArrayList<DistributionStatusOfServiceInfo>(); + Map<String, List<AuditingGenericEvent>> serviceDidMap = createServiceDidMap(distribStatusInfoList); + Set<String> didSet = serviceDidMap.keySet(); + for (String did : didSet) { + DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo(); + distributionStatusOfServiceInfo.setDistributionID(did); + String dReguestStatus = ""; + String dNotifyStatus = ""; + boolean isResult = false; + List<? extends AuditingGenericEvent> auditingGenericEventList = serviceDidMap.get(did); + ESTimeBasedEvent resAuditingGenericEvent = null; + for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { + auditingGenericEvent.fillFields(); + + String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName()); + Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName()); + if (modifierUserId != null) { + distributionStatusOfServiceInfo.setUserId((String) modifierUserId); + } + + if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) { + + isResult = true; + resAuditingGenericEvent = auditingGenericEvent; + break; + } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) { + dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent); + } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) { + dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent); + } + + resAuditingGenericEvent = auditingGenericEvent; + + } + distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName())); + + if (!isResult) { + if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) { + if (dNotifyStatus.isEmpty()) { + distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS); + + } else { + if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) + distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED); + else + distributionStatusOfServiceInfo.setDeployementStatus(ERROR); + } + } else + distributionStatusOfServiceInfo.setDeployementStatus(ERROR); + } else + distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED); + reslist.add(distributionStatusOfServiceInfo); + } + + return reslist; + } + + private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) { + String status = ""; + Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName()); + if (requestStatus instanceof String) { + status = (String) requestStatus; + } + return status; + } + + private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) { + + Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<String, List<AuditingGenericEvent>>(); + for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) { + List<AuditingGenericEvent> auditingGenericEventList = null; + String did = ""; + auditingGenericEvent.fillFields(); + + Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName()); + if (didValue != null) { + did = (String) didValue; + } + + if (!did.isEmpty()) { + if (serviceDidMap.containsKey(did)) { + auditingGenericEventList = serviceDidMap.get(did); + } + if (auditingGenericEventList == null) { + auditingGenericEventList = new ArrayList(); + + } + auditingGenericEventList.add(auditingGenericEvent); + serviceDidMap.put(did, auditingGenericEventList); + } + } + return serviceDidMap; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 54bed5ae56..ac72c98252 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -20,20 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; @@ -54,7 +41,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactType; @@ -65,10 +51,10 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.PropertyScope; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.Tag; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -91,1328 +77,1297 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.thinkaurelius.titan.core.TitanGraph; - -import fj.data.Either; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("elementsBusinessLogic") public class ElementBusinessLogic extends BaseBusinessLogic { - private static Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class.getName()); - - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private UserBusinessLogic userAdminManager; - - /** - * - * @param user - * @return - */ - public Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowed(User user) { - // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains - Either<Map<String, Set<? extends Component>>, ResponseFormat> response = null; - // Used for returning as the code requires. - Either<Map<String, List<? extends Component>>, ResponseFormat> arrayResponse = null; - - // Getting the role - String role = user.getRole(); - String userId = null; - Role currentRole = Role.valueOf(role); - - switch (currentRole) { - case DESIGNER: - userId = user.getUserId(); - response = handleDesigner(userId); - break; - - case TESTER: - userId = user.getUserId(); - response = handleTester(userId); - break; - - case GOVERNOR: - userId = user.getUserId(); - response = handleGovernor(userId); - break; - - case OPS: - userId = user.getUserId(); - response = handleOps(userId); - break; - - case PRODUCT_STRATEGIST: - userId = user.getUserId(); - response = handleProductStrategist(userId); - break; - - case PRODUCT_MANAGER: - userId = user.getUserId(); - response = handleProductManager(userId); - break; - - case ADMIN: - response = handleAdmin(); - break; - - default: - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - break; - } - //converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice) - return convertedToListResponse(response); - - } - - private Either<Map<String,List<? extends Component>>,ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) { - - Map<String, List<? extends Component>> arrayResponse = new HashMap<>(); - if (setResponse.isLeft()) { - for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) { - arrayResponse.put(entry.getKey(), (new ArrayList(new HashSet(entry.getValue())))); - } - return Either.left(arrayResponse); - } - return Either.right(setResponse.right().value()); - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleAdmin() { - Either<Map<String, Set<? extends Component>>, ResponseFormat> response; - // userId should stay null - Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); - Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates); - return response; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleDesigner(String userId) { - Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); - Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); - Either<Map<String, Set<? extends Component>>, ResponseFormat> response; - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates); - return response; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor(String userId) { - Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(null); - return result; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist(String userId) { - // Should be empty list according to Ella, 13/03/16 - Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>(); - result.put("products", new HashSet<>()); - return Either.left(result); - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductManager(String userId) { - Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); - Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); - Either<Map<String, Set<? extends Component>>, ResponseFormat> response; - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - response = getFollowedProducts(userId, lifecycleStates, lastStateStates); - return response; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps(String userId) { - Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>(); - distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); - distStatus.add(DistributionStatusEnum.DISTRIBUTED); - - Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus); - return result; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) { - - Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); - if (services.isLeft()) { - Map<String, Set<? extends Component>> result = new HashMap<>(); - Set<Service> set = new HashSet<>(); - set.addAll(services.left().value()); - result.put("services", set); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); - } - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester(String userId) { - Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either<Map<String, Set<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null); - - return result; - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) { - - try { - Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); - - if (resources.isLeft()) { - Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); - if (services.isLeft()) { - Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>(); - result.put("services", services.left().value()); - result.put("resources", resources.left().value()); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); - } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); - } - } finally { - titanDao.commit(); - } - } - - private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) { - Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); - if (products.isLeft()) { - Map<String, Set<? extends Component>> result = new HashMap<>(); - result.put("products", products.left().value()); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value()))); - } - } - - /* - * New categories flow - start - */ - public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() { - return elementOperation.getAllResourceCategories(); - } - - public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() { - return elementOperation.getAllServiceCategories(); - } - - public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY; - - User user = new User(); - Either<User, ResponseFormat> validateUser = validateUser(userId); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - String currCategoryName = (category == null ? null : category.getName()); - handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (category == null) { - log.debug("Category json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String categoryName = category.getName(); - // For auditing of failures we need the original non-normalized name - String origCategoryName = categoryName; - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) { - log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) { - log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - category.setName(categoryName); - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); - category.setNormalizedName(normalizedName); - - NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType); - - Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName); - if (categoryUniqueEither.isRight()) { - log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isCategoryUnique = categoryUniqueEither.left().value(); - if (!isCategoryUnique) { - log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType); - if (createCategoryByType.isRight()) { - log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value())); - } - category = createCategoryByType.left().value(); - log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType); - return Either.left(category); - } - - public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY; - // For auditing - String parentCategoryName = parentCategoryId; - - if (subCategory == null) { - log.debug("Sub-category json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String subCategoryName = subCategory.getName(); - // For auditing of failures we need the original non-normalized name - String origSubCategoryName = subCategoryName; - - User user = new User(); - Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); - if (validateComponentType.isRight()) { - log.debug("Validation of component type for sub-category failed"); - ResponseFormat responseFormat = validateComponentType.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - - CategoryDefinition categoryDefinition; - Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum); - if (validateCategoryExists.isRight()) { - log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId); - ResponseFormat responseFormat = validateCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryDefinition = validateCategoryExists.left().value(); - parentCategoryName = categoryDefinition.getName(); - - if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) { - log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) { - log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName); - subCategory.setNormalizedName(normalizedName); - - // Uniqueness under this category - Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId); - if (subCategoryUniqueForCategory.isRight()) { - log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isSubUnique = subCategoryUniqueForCategory.left().value(); - if (!isSubUnique) { - log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - // Setting name of subcategory to fit the similar subcategory name - // ignoring cases. - // For example if Network-->kUKU exists for service category Network, - // and user is trying to create Router-->Kuku for service category - // Router, - // his subcategory name will be Router-->kUKU. - Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName); - if (subCategoryUniqueForType.isRight()) { - log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value(); - if (subCategoryDefinition != null) { - subCategoryName = subCategoryDefinition.getName(); - } - - subCategory.setName(subCategoryName); - ///////////////////////////////////////////// Validations end - - Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType); - if (createSubCategory.isRight()) { - log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - SubCategoryDefinition subCategoryCreated = createSubCategory.left().value(); - log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType); - return Either.left(subCategoryCreated); - } - - public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING; - // For auditing - String parentCategoryName = grandParentCategoryId; - String parentSubCategoryName = parentSubCategoryId; - - User user; - Either<User, ResponseFormat> validateUser = validateUserExists(userId, "create Grouping", false); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - String groupingNameForAudit = (grouping == null ? null : grouping.getName()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (grouping == null) { - log.debug("Grouping json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String groupingName = grouping.getName(); - // For auditing of failures we need the original non-normalized name - String origGroupingName = groupingName; - - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); - if (validateComponentType.isRight()) { - log.debug("Validation of component type for grouping failed"); - ResponseFormat responseFormat = validateComponentType.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); - - // Validate category - CategoryDefinition categoryDefinition; - Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum); - if (validateCategoryExists.isRight()) { - log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId); - ResponseFormat responseFormat = validateCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryDefinition = validateCategoryExists.left().value(); - parentCategoryName = categoryDefinition.getName(); - - // Validate subcategory - SubCategoryDefinition subCategoryDefinition; - Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum); - if (validateSubCategoryExists.isRight()) { - log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId); - ResponseFormat responseFormat = validateSubCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - subCategoryDefinition = validateSubCategoryExists.left().value(); - parentSubCategoryName = subCategoryDefinition.getName(); - - if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) { - log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) { - log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName); - grouping.setNormalizedName(normalizedName); - - // Uniqueness under this category - Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId); - if (groupingUniqueForSubCategory.isRight()) { - log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value(); - if (!isGroupingUnique) { - log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - // Setting name of grouping to fit the similar grouping name ignoring - // cases. - // For example if Network-->kUKU exists for service sub-category - // Network, and user is trying to create grouping Router-->Kuku for - // service sub-category Router, - // his grouping name will be Router-->kUKU. - Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName); - if (groupingUniqueForType.isRight()) { - log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - GroupingDefinition groupingDefinition = groupingUniqueForType.left().value(); - if (groupingDefinition != null) { - groupingName = groupingDefinition.getName(); - } - - grouping.setName(groupingName); - ///////////////////////////////////////////// Validations end - - Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType); - if (createGrouping.isRight()) { - log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - GroupingDefinition groupingCreated = createGrouping.left().value(); - log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType); - return Either.left(groupingCreated); - } - - public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) { - AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; - ResponseFormat responseFormat; - User user = new User(); - if (userId == null) { - user.setUserId("UNKNOWN"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - - Either<User, ResponseFormat> validateUser = validateUserExists(userId, "get All Categories", false); - if (validateUser.isRight()) { - user.setUserId(userId); - log.debug("Validation of user failed, userId {}", userId); - responseFormat = validateUser.right().value(); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - user = validateUser.left().value(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum == null) { - log.debug("Cannot create category for component type {}", componentType); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type"); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false); - if (getAllCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - List<CategoryDefinition> categories = getAllCategoriesByType.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.left(categories); - } - - public Either<UiCategories, ResponseFormat> getAllCategories(String userId) { - AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; - ResponseFormat responseFormat; - UiCategories categories = new UiCategories(); - - Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false); - - if (userResponse.isRight()) { - return Either.right(userResponse.right().value()); - } - User user = userResponse.left().value(); - - //GET resource categories - Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); - if (getResourceCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat); - return Either.right(responseFormat); - } - categories.setResourceCategories(getResourceCategoriesByType.left().value()); - - //GET service categories - Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false); - if (getServiceCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); - return Either.right(responseFormat); - } - categories.setServiceCategories(getServiceCategoriesByType.left().value()); - - //GET product categories - Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); - if (getProductCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); - return Either.right(responseFormat); - } - - categories.setProductCategories(getProductCategoriesByType.left().value()); - return Either.left(categories); - - } - - public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Category", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot create category for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - - Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId); - if (deleteCategoryByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value())); - } - CategoryDefinition category = deleteCategoryByType.left().value(); - log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId()); - return Either.left(category); - } - - public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Sub Category", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot delete sub-category for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - - Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId); - if (deleteSubCategoryByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value())); - } - SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value(); - log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId()); - return Either.left(subCategory); - } - - public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Grouping", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot delete grouping for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); - - Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId); - if (deleteGroupingByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value())); - } - GroupingDefinition deletedGrouping = deleteGroupingByType.left().value(); - log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId()); - return Either.left(deletedGrouping); - } - - private Either<User, ResponseFormat> validateUser(String userId) { - - // validate user exists - if (userId == null) { - log.debug("UserId is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); - } - - Either<User, ActionStatus> userResult = userAdminManager.getUser(userId, false); - if (userResult.isRight()) { - ResponseFormat responseFormat; - if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("Not authorized user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("Failed to authorize user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); - } - - return Either.right(responseFormat); - } - return Either.left(userResult.left().value()); - // ========================================- - } - - private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) { - String role = user.getRole(); - boolean validAdminAction = (role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE)); - boolean validProductAction = (role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT)); - - if (!(validAdminAction || validProductAction)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) { - boolean validResourceAction = (componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY)); - boolean validServiceAction = (componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY); - boolean validProductAction = (componentType == ComponentTypeEnum.PRODUCT); // can - // be - // any - // category - // type - - if (!(validResourceAction || validServiceAction || validProductAction)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) { - Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId); - if (categoryByTypeAndId.isRight()) { - log.debug("Failed to fetch parent category, parent categoryId {}", categoryId); - ActionStatus actionStatus = categoryByTypeAndId.right().value(); - ResponseFormat responseFormat; - if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), ""); - } else { - responseFormat = componentsUtils.getResponseFormat(actionStatus); - } - return Either.right(responseFormat); - } - return Either.left(categoryByTypeAndId.left().value()); - } - - private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) { - Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId); - if (subCategoryByTypeAndId.isRight()) { - log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId); - ActionStatus actionStatus = subCategoryByTypeAndId.right().value(); - ResponseFormat responseFormat; - if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), ""); - } else { - responseFormat = componentsUtils.getResponseFormat(actionStatus); - } - return Either.right(responseFormat); - } - return Either.left(subCategoryByTypeAndId.left().value()); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType); - } - - /* - * New categories flow - end - */ - - public Either<List<Tag>, ActionStatus> getAllTags(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Tags"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllTags(); - } - - public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Property Scopes"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllPropertyScopes(); - } - - public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes(String userId) { - Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Artifact Types"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllArtifactTypes(); - } - - public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { - return elementOperation.getAllDeploymentArtifactTypes(); - } - - public Either<Integer, ActionStatus> getDefaultHeatTimeout() { - return elementOperation.getDefaultHeatTimeout(); - } - - public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Map<String, List<? extends Component>> resMap = new HashMap<>(); - - Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE,excludeTypes, true); - if (resResources.isLeft()) { - Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE,excludeTypes, true); - if (resServices.isLeft()) { - // Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); - // if (resProducts.isLeft()) { - resMap.put("resources", resResources.left().value()); - resMap.put("services", resServices.left().value()); - resMap.put("products", new ArrayList<>()); - - return Either.left(resMap); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resServices.right().value()))); - } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resResources.right().value()))); - } - } - - public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) { - ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); - - if (query != null) { - Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum); - if (invalidFilter.isPresent()) { - log.debug("getFilteredAssetList: invalid filter key"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString())); - } - } - - if (filters == null || filters.isEmpty()) { - Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum,null, false); - if(componentsList.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); - } - return Either.left(componentsList.left().value()); - } - - Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false); - - // category hierarchy mismatch or category/subCategory/distributionStatus not found - if (result.isRight()) { - List<String> params = getErrorResponseParams(filters, assetTypeEnum); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2))); - } - if (result.left().value().isEmpty()) {// no assets found for requested - // criteria - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query)); - } - return Either.left(result.left().value()); - } - - private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) { - Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); - if(assetType == ComponentTypeEnum.RESOURCE){ - - assetResult = getFilteredResouces(filters, inTransaction); - - } else if (assetType == ComponentTypeEnum.SERVICE){ - - assetResult = getFilteredServices(filters, inTransaction); - } - return assetResult; - } - - private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) { - - Either<List<T>, StorageOperationStatus> components = null; - - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); - DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); - if (distributionStatus != null && distEnum == null) { - filters.remove(FilterKeyEnum.CATEGORY); - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - - if (categoryName != null) { // primary filter - components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); - if (components.isLeft() && distEnum != null) {// secondary filter - Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); - return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); - } - filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); - return components; - } - - Set<DistributionStatusEnum> distStatusSet = new HashSet<>(); - distStatusSet.add(distEnum); - Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null); - if (servicesWithDistStatus.isRight()) { // not found == empty list - return Either.left(new ArrayList<>()); - } - - return Either.left((List<T>)servicesWithDistStatus.left().value()); - } - - public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) { - - if (assetType == null || assetType == null) { - log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); - - if (assetTypeEnum == null) { - log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - switch (assetTypeEnum) { - case RESOURCE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); - if(componentsListByUuid.isRight()) { - log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue()+ " fetching failed"); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum); - return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid)); - } - - log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful"); - return Either.left(componentsListByUuid.left().value()); - } - - public List<String> getAllComponentTypesParamNames() { - List<String> paramNames = new ArrayList<>(); - paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME); - paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME); - paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME); - return paramNames; - } - - public List<String> getAllSupportedRoles() { - Role[] values = Role.values(); - List<String> roleNames = new ArrayList<>(); - for (Role role : values) { - roleNames.add(role.name()); - } - return roleNames; - } - - public Either<Map<String, String>, ActionStatus> getResourceTypesMap() { - return elementOperation.getResourceTypesMap(); - } - - private Optional<NameValuePair> findInvalidFilter(String query, ComponentTypeEnum assetType) { - List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8); - List<String> validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType); - Predicate<NameValuePair> noMatch = p -> !validKeys.contains(p.getName()); - return params.stream().filter(noMatch).findAny(); - } - - private List<String> getErrorResponseParams(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType) { - List<String> params = new ArrayList<String>(); - if (1 == filters.size()) { - params.add(assetType.getValue().toLowerCase()); - params.add(filters.keySet().iterator().next().getName()); - params.add(filters.values().iterator().next()); - } else { - params.add(assetType.getValue()); - params.add(filters.get(FilterKeyEnum.SUB_CATEGORY)); - params.add(filters.get(FilterKeyEnum.CATEGORY)); - } - return params; - } - - public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) { - - String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE)); - Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null; - Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData; - - if (categoryName != null) { - subcategories = getAllSubCategories(categoryName); - if (subcategories.isRight()) { - filters.remove(FilterKeyEnum.SUB_CATEGORY); - return Either.right(subcategories.right().value()); - } - } - if (subCategoryName != null) { // primary filter - if (categoryName != null) { - subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); - if (!subCategoryData.isPresent()) { - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, - ResourceMetadataData.class, resourceType); - } - - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); - } - if(subcategories != null){ - return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); - } - return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction); - } - - private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) { - Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - return Either.right(categoryResult.right().value()); - } - CategoryData categoryData = categoryResult.left().value(); - - Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); - if (childrenNodes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); - } - return Either.left(childrenNodes.left().value()); - } - - private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) { - Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); - return childNodes.stream().filter(matchName).findAny(); - } - - protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz, ResourceTypeEnum resourceType) { - try { - Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType); - - } finally { - if (false == inTransaction) { - titanDao.commit(); - } - } - } - - protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz, ResourceTypeEnum resourceType) { - List<T> components = new ArrayList<>(); - try { - Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); - if (getCategory.isRight()) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - for (GraphNode category : getCategory.left().value()) { - Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); - if (result.isRight()) { - return result; - } - components.addAll(result.left().value()); - } - - return Either.left(components); - } finally { - if (false == inTransaction) { - titanDao.commit(); - } - } - } - - private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) { - List<T> components = new ArrayList<>(); - Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); - if (parentNodes.isLeft()) { - for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) { - ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); - Boolean isHighest = componentData.isHighestVersion(); - boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); - - if (isHighest && isMatchingResourceType) { - Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (result.isRight()) { - return Either.right(result.right().value()); - } - components.add(result.left().value()); - } - } - } - return Either.left(components); - } - - private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, - ComponentMetadataDataDefinition componentData) { - - boolean isMatching; - if (componentType == NodeTypeEnum.Resource) { - if (resourceType == null) { - isMatching = true; - } else { - isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType(); - } - } else { - isMatching = true; - } - return isMatching; - } - - private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { - List<T> components = new ArrayList<>(); - - for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) { - Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, - inTransaction, ResourceMetadataData.class, resourceType); - if (fetched.isRight()) { - // return fetched; - continue; - } - components.addAll(fetched.left().value()); - } - return Either.left(components); - } - - private Either<List<Component>, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) { - List<Component> components = null; - StorageOperationStatus status; - Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>(); - Either<List<Component>, StorageOperationStatus> result; - try { - ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue())); - Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter); - if (getResources.isRight()) { - status = getResources.right().value(); - if(status != StorageOperationStatus.NOT_FOUND){ - statusWrapper.setInnerElement(getResources.right().value()); - }else{ - components = new ArrayList<>(); - } - } else{ - components = getResources.left().value(); - } - if(!statusWrapper.isEmpty()){ - result = Either.right(statusWrapper.getInnerElement()); - }else{ - result = Either.left(components); - } - return result; - } finally { - if (!inTransaction) { - titanDao.commit(); - } - } - } - - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - return convertResourceDataToResource((ResourceMetadataData) componentMetadataData); - } - private Resource convertResourceDataToResource(ResourceMetadataData resourceData) { - - ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()); - - Resource resource = new Resource(resourceMetadataDataDefinition); - - return resource; - } - private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) { - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction); - } - - private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, boolean inTransaction) { - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); - Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List<Service> services = new ArrayList<Service>(); - List<ServiceMetadataData> servicesDataList = byCriteria.left().value(); - for (ServiceMetadataData data : servicesDataList) { - Either<Component, StorageOperationStatus> service = toscaOperationFacade.getToscaElement(data.getMetadataDataDefinition().getUniqueId()); - if (service.isLeft()) { - services.add((Service)service.left().value()); - } else { - log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId()); - } - } - return Either.left(services); - } - + private static final Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class); + + @javax.annotation.Resource + private IElementOperation elementOperation; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private UserBusinessLogic userAdminManager; + + /** + * + * @param user + * @return + */ + public Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowed(User user) { + // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains + Either<Map<String, Set<? extends Component>>, ResponseFormat> response = null; + // Getting the role + String role = user.getRole(); + String userId = null; + Role currentRole = Role.valueOf(role); + + switch (currentRole) { + case DESIGNER: + userId = user.getUserId(); + response = handleDesigner(userId); + break; + + case TESTER: + userId = user.getUserId(); + response = handleTester(userId); + break; + + case GOVERNOR: + userId = user.getUserId(); + response = handleGovernor(userId); + break; + + case OPS: + userId = user.getUserId(); + response = handleOps(userId); + break; + + case PRODUCT_STRATEGIST: + userId = user.getUserId(); + response = handleProductStrategist(userId); + break; + + case PRODUCT_MANAGER: + userId = user.getUserId(); + response = handleProductManager(userId); + break; + + case ADMIN: + response = handleAdmin(); + break; + + default: + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + break; + } + // converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice) + return convertedToListResponse(response); + + } + + private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) { + + Map<String, List<? extends Component>> arrayResponse = new HashMap<>(); + if (setResponse.isLeft()) { + for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) { + arrayResponse.put(entry.getKey(), new ArrayList(new HashSet(entry.getValue()))); + } + return Either.left(arrayResponse); + } + return Either.right(setResponse.right().value()); + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleAdmin() { + Either<Map<String, Set<? extends Component>>, ResponseFormat> response; + // userId should stay null + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates); + return response; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleDesigner(String userId) { + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); + Either<Map<String, Set<? extends Component>>, ResponseFormat> response; + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + // more states + lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates); + return response; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor(String userId) { + Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(null); + return result; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist(String userId) { + // Should be empty list according to Ella, 13/03/16 + Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>(); + result.put("products", new HashSet<>()); + return Either.left(result); + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductManager(String userId) { + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); + Either<Map<String, Set<? extends Component>>, ResponseFormat> response; + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + // more states + lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + response = getFollowedProducts(userId, lifecycleStates, lastStateStates); + return response; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps(String userId) { + Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>(); + distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); + distStatus.add(DistributionStatusEnum.DISTRIBUTED); + + Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus); + return result; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) { + + Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); + if (services.isLeft()) { + Map<String, Set<? extends Component>> result = new HashMap<>(); + Set<Service> set = new HashSet<>(); + set.addAll(services.left().value()); + result.put("services", set); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + } + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester(String userId) { + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<Map<String, Set<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null); + + return result; + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) { + + try { + Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); + + if (resources.isLeft()) { + Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); + if (services.isLeft()) { + Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>(); + result.put("services", services.left().value()); + result.put("resources", resources.left().value()); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + } + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); + } + } finally { + titanDao.commit(); + } + } + + private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) { + Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); + if (products.isLeft()) { + Map<String, Set<? extends Component>> result = new HashMap<>(); + result.put("products", products.left().value()); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value()))); + } + } + + /* + * New categories flow - start + */ + public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() { + return elementOperation.getAllResourceCategories(); + } + + public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() { + return elementOperation.getAllServiceCategories(); + } + + public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY; + + User user = new User(); + Either<User, ResponseFormat> validateUser = validateUser(userId); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + String currCategoryName = (category == null ? null : category.getName()); + handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (category == null) { + log.debug("Category json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String categoryName = category.getName(); + // For auditing of failures we need the original non-normalized name + String origCategoryName = categoryName; + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) { + log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) { + log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + category.setName(categoryName); + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); + category.setNormalizedName(normalizedName); + + NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType); + + Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName); + if (categoryUniqueEither.isRight()) { + log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isCategoryUnique = categoryUniqueEither.left().value(); + if (!isCategoryUnique) { + log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType); + if (createCategoryByType.isRight()) { + log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value())); + } + category = createCategoryByType.left().value(); + log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType); + return Either.left(category); + } + + public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY; + // For auditing + String parentCategoryName = parentCategoryId; + + if (subCategory == null) { + log.debug("Sub-category json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String subCategoryName = subCategory.getName(); + // For auditing of failures we need the original non-normalized name + String origSubCategoryName = subCategoryName; + + User user = new User(); + Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); + if (validateComponentType.isRight()) { + log.debug("Validation of component type for sub-category failed"); + ResponseFormat responseFormat = validateComponentType.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + + CategoryDefinition categoryDefinition; + Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum); + if (validateCategoryExists.isRight()) { + log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId); + ResponseFormat responseFormat = validateCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryDefinition = validateCategoryExists.left().value(); + parentCategoryName = categoryDefinition.getName(); + + if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) { + log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) { + log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName); + subCategory.setNormalizedName(normalizedName); + + // Uniqueness under this category + Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId); + if (subCategoryUniqueForCategory.isRight()) { + log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isSubUnique = subCategoryUniqueForCategory.left().value(); + if (!isSubUnique) { + log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + // Setting name of subcategory to fit the similar subcategory name + // ignoring cases. + // For example if Network-->kUKU exists for service category Network, + // and user is trying to create Router-->Kuku for service category + // Router, + // his subcategory name will be Router-->kUKU. + Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName); + if (subCategoryUniqueForType.isRight()) { + log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value(); + if (subCategoryDefinition != null) { + subCategoryName = subCategoryDefinition.getName(); + } + + subCategory.setName(subCategoryName); + ///////////////////////////////////////////// Validations end + + Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType); + if (createSubCategory.isRight()) { + log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + SubCategoryDefinition subCategoryCreated = createSubCategory.left().value(); + log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType); + return Either.left(subCategoryCreated); + } + + public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING; + // For auditing + String parentCategoryName = grandParentCategoryId; + String parentSubCategoryName = parentSubCategoryId; + + User user; + Either<User, ResponseFormat> validateUser = validateUserExists(userId, "create Grouping", false); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + String groupingNameForAudit = grouping == null ? null : grouping.getName(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (grouping == null) { + log.debug("Grouping json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String groupingName = grouping.getName(); + // For auditing of failures we need the original non-normalized name + String origGroupingName = groupingName; + + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); + if (validateComponentType.isRight()) { + log.debug("Validation of component type for grouping failed"); + ResponseFormat responseFormat = validateComponentType.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); + + // Validate category + CategoryDefinition categoryDefinition; + Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum); + if (validateCategoryExists.isRight()) { + log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId); + ResponseFormat responseFormat = validateCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryDefinition = validateCategoryExists.left().value(); + parentCategoryName = categoryDefinition.getName(); + + // Validate subcategory + SubCategoryDefinition subCategoryDefinition; + Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum); + if (validateSubCategoryExists.isRight()) { + log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId); + ResponseFormat responseFormat = validateSubCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + subCategoryDefinition = validateSubCategoryExists.left().value(); + parentSubCategoryName = subCategoryDefinition.getName(); + + if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) { + log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) { + log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName); + grouping.setNormalizedName(normalizedName); + + // Uniqueness under this category + Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId); + if (groupingUniqueForSubCategory.isRight()) { + log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value(); + if (!isGroupingUnique) { + log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + // Setting name of grouping to fit the similar grouping name ignoring + // cases. + // For example if Network-->kUKU exists for service sub-category + // Network, and user is trying to create grouping Router-->Kuku for + // service sub-category Router, + // his grouping name will be Router-->kUKU. + Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName); + if (groupingUniqueForType.isRight()) { + log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + GroupingDefinition groupingDefinition = groupingUniqueForType.left().value(); + if (groupingDefinition != null) { + groupingName = groupingDefinition.getName(); + } + + grouping.setName(groupingName); + ///////////////////////////////////////////// Validations end + + Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType); + if (createGrouping.isRight()) { + log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + GroupingDefinition groupingCreated = createGrouping.left().value(); + log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType); + return Either.left(groupingCreated); + } + + public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) { + AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; + ResponseFormat responseFormat; + User user = new User(); + if (userId == null) { + user.setUserId("UNKNOWN"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + + Either<User, ResponseFormat> validateUser = validateUserExists(userId, "get All Categories", false); + if (validateUser.isRight()) { + user.setUserId(userId); + log.debug("Validation of user failed, userId {}", userId); + responseFormat = validateUser.right().value(); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + user = validateUser.left().value(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum == null) { + log.debug("Cannot create category for component type {}", componentType); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type"); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false); + if (getAllCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + List<CategoryDefinition> categories = getAllCategoriesByType.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.left(categories); + } + + public Either<UiCategories, ResponseFormat> getAllCategories(String userId) { + AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; + ResponseFormat responseFormat; + UiCategories categories = new UiCategories(); + + Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false); + + if (userResponse.isRight()) { + return Either.right(userResponse.right().value()); + } + User user = userResponse.left().value(); + + // GET resource categories + Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); + if (getResourceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setResourceCategories(getResourceCategoriesByType.left().value()); + + // GET service categories + Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false); + if (getServiceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setServiceCategories(getServiceCategoriesByType.left().value()); + + // GET product categories + Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); + if (getProductCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); + return Either.right(responseFormat); + } + + categories.setProductCategories(getProductCategoriesByType.left().value()); + return Either.left(categories); + + } + + public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Category", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot create category for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + + Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId); + if (deleteCategoryByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value())); + } + CategoryDefinition category = deleteCategoryByType.left().value(); + log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId()); + return Either.left(category); + } + + public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Sub Category", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot delete sub-category for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + + Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId); + if (deleteSubCategoryByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value())); + } + SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value(); + log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId()); + return Either.left(subCategory); + } + + public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Grouping", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot delete grouping for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); + + Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId); + if (deleteGroupingByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value())); + } + GroupingDefinition deletedGrouping = deleteGroupingByType.left().value(); + log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId()); + return Either.left(deletedGrouping); + } + + private Either<User, ResponseFormat> validateUser(String userId) { + + // validate user exists + if (userId == null) { + log.debug("UserId is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); + } + + Either<User, ActionStatus> userResult = userAdminManager.getUser(userId, false); + if (userResult.isRight()) { + ResponseFormat responseFormat; + if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("Not authorized user, userId = {}", userId); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } else { + log.debug("Failed to authorize user, userId = {}", userId); + responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); + } + + return Either.right(responseFormat); + } + return Either.left(userResult.left().value()); + // ========================================- + } + + private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) { + String role = user.getRole(); + boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE); + boolean validProductAction = role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT); + + if (!(validAdminAction || validProductAction)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) { + boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY); + boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY; + boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can + // be + // any + // category + // type + + if (!(validResourceAction || validServiceAction || validProductAction)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) { + Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId); + if (categoryByTypeAndId.isRight()) { + log.debug("Failed to fetch parent category, parent categoryId {}", categoryId); + ActionStatus actionStatus = categoryByTypeAndId.right().value(); + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), ""); + } else { + responseFormat = componentsUtils.getResponseFormat(actionStatus); + } + return Either.right(responseFormat); + } + return Either.left(categoryByTypeAndId.left().value()); + } + + private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) { + Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId); + if (subCategoryByTypeAndId.isRight()) { + log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId); + ActionStatus actionStatus = subCategoryByTypeAndId.right().value(); + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), ""); + } else { + responseFormat = componentsUtils.getResponseFormat(actionStatus); + } + return Either.right(responseFormat); + } + return Either.left(subCategoryByTypeAndId.left().value()); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType); + } + + /* + * New categories flow - end + */ + + public Either<List<Tag>, ActionStatus> getAllTags(String userId) { + Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Tags"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllTags(); + } + + public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes(String userId) { + Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Property Scopes"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllPropertyScopes(); + } + + public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes(String userId) { + Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Artifact Types"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllArtifactTypes(); + } + + public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { + return elementOperation.getAllDeploymentArtifactTypes(); + } + + public Either<Integer, ActionStatus> getDefaultHeatTimeout() { + return elementOperation.getDefaultHeatTimeout(); + } + + public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId) { + try { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", true); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return toscaOperationFacade.getCatalogComponents().bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); + } finally { + titanDao.commit(); + } + } + + private Map<String, List<CatalogComponent>> groupByComponentType(List<CatalogComponent> components) { + Map<String, List<CatalogComponent>> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType()))); + + // fixed response for UI!!! UI need to receive always map! + if (map == null) { + map = new HashMap<>(); + } + if (map.get("resources") == null) { + map.put("resources", new ArrayList()); + } + if (map.get("services") == null) { + map.put("services", new ArrayList()); + } + return map; + } + + private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) { + switch (componentTypeEnum) { + case RESOURCE: + return "resources"; + case SERVICE: + return "services"; + default: + throw new IllegalStateException("resources or services only"); + } + } + + public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) { + ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); + + if (query != null) { + Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum); + if (invalidFilter.isPresent()) { + log.debug("getFilteredAssetList: invalid filter key"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString())); + } + } + + if (filters == null || filters.isEmpty()) { + Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, null, false); + if (componentsList.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); + } + return Either.left(componentsList.left().value()); + } + + Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false); + + // category hierarchy mismatch or category/subCategory/distributionStatus not found + if (result.isRight()) { + List<String> params = getErrorResponseParams(filters, assetTypeEnum); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2))); + } + if (result.left().value().isEmpty()) {// no assets found for requested + // criteria + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query)); + } + return Either.left(result.left().value()); + } + + private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) { + Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); + if (assetType == ComponentTypeEnum.RESOURCE) { + + assetResult = getFilteredResouces(filters, inTransaction); + + } else if (assetType == ComponentTypeEnum.SERVICE) { + + assetResult = getFilteredServices(filters, inTransaction); + } + return assetResult; + } + + private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) { + + Either<List<T>, StorageOperationStatus> components = null; + + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); + DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); + if (distributionStatus != null && distEnum == null) { + filters.remove(FilterKeyEnum.CATEGORY); + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + + if (categoryName != null) { // primary filter + components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); + if (components.isLeft() && distEnum != null) {// secondary filter + Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); + return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); + } + filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); + return components; + } + + Set<DistributionStatusEnum> distStatusSet = new HashSet<>(); + distStatusSet.add(distEnum); + Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null); + if (servicesWithDistStatus.isRight()) { // not found == empty list + return Either.left(new ArrayList<>()); + } + + return Either.left((List<T>) servicesWithDistStatus.left().value()); + } + + public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) { + + if (assetType == null || uuid == null) { + log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); + + if (assetTypeEnum == null) { + log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + + switch (assetTypeEnum) { + case RESOURCE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); + if (componentsListByUuid.isRight()) { + log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + " fetching failed"); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum); + return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid)); + } + + log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful"); + return Either.left(componentsListByUuid.left().value()); + } + + public List<String> getAllComponentTypesParamNames() { + List<String> paramNames = new ArrayList<>(); + paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME); + paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME); + paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME); + return paramNames; + } + + public List<String> getAllSupportedRoles() { + Role[] values = Role.values(); + List<String> roleNames = new ArrayList<>(); + for (Role role : values) { + roleNames.add(role.name()); + } + return roleNames; + } + + public Either<Map<String, String>, ActionStatus> getResourceTypesMap() { + return elementOperation.getResourceTypesMap(); + } + + private Optional<NameValuePair> findInvalidFilter(String query, ComponentTypeEnum assetType) { + List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8); + List<String> validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType); + Predicate<NameValuePair> noMatch = p -> !validKeys.contains(p.getName()); + return params.stream().filter(noMatch).findAny(); + } + + private List<String> getErrorResponseParams(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType) { + List<String> params = new ArrayList<String>(); + if (1 == filters.size()) { + params.add(assetType.getValue().toLowerCase()); + params.add(filters.keySet().iterator().next().getName()); + params.add(filters.values().iterator().next()); + } else { + params.add(assetType.getValue()); + params.add(filters.get(FilterKeyEnum.SUB_CATEGORY)); + params.add(filters.get(FilterKeyEnum.CATEGORY)); + } + return params; + } + + public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) { + + String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + ResourceTypeEnum resourceType = ResourceTypeEnum.getType(filters.get(FilterKeyEnum.RESOURCE_TYPE)); + Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null; + Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData; + + if (categoryName != null) { + subcategories = getAllSubCategories(categoryName); + if (subcategories.isRight()) { + filters.remove(FilterKeyEnum.SUB_CATEGORY); + return Either.right(subcategories.right().value()); + } + } + if (subCategoryName != null) { // primary filter + if (categoryName != null) { + subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); + if (!subCategoryData.isPresent()) { + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, + ResourceMetadataData.class, resourceType); + } + + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); + } + if (subcategories != null) { + return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); + } + return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction); + } + + private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) { + Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); + if (categoryResult.isRight()) { + return Either.right(categoryResult.right().value()); + } + CategoryData categoryData = categoryResult.left().value(); + + Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), + GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); + if (childrenNodes.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); + } + return Either.left(childrenNodes.left().value()); + } + + private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) { + Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); + return childNodes.stream().filter(matchName).findAny(); + } + + protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class<S> clazz, ResourceTypeEnum resourceType) { + try { + return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType); + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class<S> clazz, ResourceTypeEnum resourceType) { + List<T> components = new ArrayList<>(); + try { + Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; + Map<String, Object> props = new HashMap<String, Object>(); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); + if (getCategory.isRight()) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + for (GraphNode category : getCategory.left().value()) { + Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); + if (result.isRight()) { + return result; + } + components.addAll(result.left().value()); + } + + return Either.left(components); + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) { + List<T> components = new ArrayList<>(); + Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); + if (parentNodes.isLeft()) { + for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) { + ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); + Boolean isHighest = componentData.isHighestVersion(); + boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); + boolean isDeleted = componentData.isDeleted() != null && componentData.isDeleted(); + + if (isHighest && isMatchingResourceType && !isDeleted) { + Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (result.isRight()) { + return Either.right(result.right().value()); + } + components.add(result.left().value()); + } + } + } + return Either.left(components); + } + + private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) { + + boolean isMatching; + if (componentType == NodeTypeEnum.Resource) { + if (resourceType == null) { + isMatching = true; + } else { + isMatching = resourceType == ((ResourceMetadataDataDefinition) componentData).getResourceType(); + } + } else { + isMatching = true; + } + return isMatching; + } + + private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { + List<T> components = new ArrayList<>(); + + for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) { + Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, + inTransaction, ResourceMetadataData.class, resourceType); + if (fetched.isRight()) { + continue; + } + components.addAll(fetched.left().value()); + } + return Either.left(components); + } + + private Either<List<Component>, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) { + List<Component> components = null; + StorageOperationStatus status; + Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>(); + Either<List<Component>, StorageOperationStatus> result; + try { + ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue())); + Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter); + if (getResources.isRight()) { + status = getResources.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + statusWrapper.setInnerElement(getResources.right().value()); + } else { + components = new ArrayList<>(); + } + } else { + components = getResources.left().value(); + } + if (!statusWrapper.isEmpty()) { + result = Either.right(statusWrapper.getInnerElement()); + } else { + result = Either.left(components); + } + return result; + } finally { + if (!inTransaction) { + titanDao.commit(); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java new file mode 100644 index 0000000000..7233ba7657 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by yavivi on 04/02/2018. + */ +@org.springframework.stereotype.Component +public class ExternalRefsBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(ExternalRefsBusinessLogic.class); + + private ExternalReferencesOperation externalReferencesOperation; + private ToscaOperationFacade toscaOperationFacade; + private GraphLockOperation graphLockOperation; + + public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, GraphLockOperation graphLockOperation){ + this.externalReferencesOperation = externalReferencesOperation; + this.toscaOperationFacade = toscaOperationFacade; + this.graphLockOperation = graphLockOperation; + } + + public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){ + Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version); + if (componentsResult == null || componentsResult.isRight()) { + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + Component component = componentsResult.left().value(); + return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType); + } + + public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType){ + Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version); + if (componentsResult == null || componentsResult.isRight()) { + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + Component component = componentsResult.left().value(); + + Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), objectType); + if (externalReferencesResult.isRight()){ + return Either.right(externalReferencesResult.right().value()); + } else { + return Either.left(externalReferencesResult.left().value()); + } + } + + public Either<String, ActionStatus> addExternalReference(String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) { + return this.doAction("POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), ""); + } + + + public Either<String, ActionStatus> deleteExternalReference(String uuid, String componentInstanceName, String objectType, String reference) { + return this.doAction("DELETE", uuid, componentInstanceName, objectType, reference, ""); + } + + public Either<String, ActionStatus> updateExternalReference(String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) { + return this.doAction("PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue); + } + + private Either<String, ActionStatus> doAction(String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){ + Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch()); + if (latestServiceByUuid == null || latestServiceByUuid.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + //Get Component Unique ID + Component component = latestServiceByUuid.left().value(); + String uniqueId = component.getUniqueId(); + + //Lock Asset + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service); + if (lockStatus != StorageOperationStatus.OK){ + return Either.right(ActionStatus.GENERAL_ERROR); + } + + Either<String, ActionStatus> opResult = Either.right(ActionStatus.GENERAL_ERROR); + try { + switch (action) { + case "POST": + opResult = this.externalReferencesOperation.addExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); + break; + case "PUT": + opResult = this.externalReferencesOperation.updateExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1, ref2); + break; + case "DELETE": + opResult = this.externalReferencesOperation.deleteExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); + break; + default: + break; + } + } catch (Exception e) { + opResult = Either.right(ActionStatus.GENERAL_ERROR); + log.error("Failed to execute external ref action:{} on asset:{} component:{} objectType:{}", action, uuid, componentInstanceName, objectType); + log.error("Cause is:" , e); + } finally { + //Unlock Asset + this.graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service); + } + return opResult; + } + + private Map<GraphPropertyEnum, Object> createPropsToMatch() { + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + return propertiesToMatch; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index de571b0f03..63b72b932e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -20,29 +20,20 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.utils.Utils; +import org.openecomp.sdc.be.components.validation.AccessValidations; +import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; @@ -69,2084 +60,1666 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; -import fj.data.Either; +import static java.util.stream.Collectors.toList; @org.springframework.stereotype.Component("groupBusinessLogic") public class GroupBusinessLogic extends BaseBusinessLogic { - private static String ADDING_GROUP = "AddingGroup"; - - public static final String INITIAL_VERSION = "1"; - - private static final String CREATE_GROUP = "CreateGroup"; - - private static final String UPDATE_GROUP = "UpdateGroup"; - - private static final String GET_GROUP = "GetGroup"; - - private static Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class.getName()); - - public GroupBusinessLogic() { - - } - - @javax.annotation.Resource - private GroupTypeOperation groupTypeOperation; - - @Autowired - ArtifactsOperations artifactsOperation; - - @Autowired - private GroupsOperation groupsOperation; - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - /** - * - * 1. validate user exist - * - * 2. validate component can be edited - * - * 3. verify group not already exist - * - * 4. verify type of group exist - * - * 5. verify Component instances exist under the component - * - * 6. verify the component instances type are allowed according to the member types in the group type - * - * 7. verify the artifacts belongs to the component - * - * @param componentId - * @param userId - * @param componentType - * @param groupDefinition - * @param inTransaction - * @return - */ - /* - * public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - * - * Either<GroupDefinition, ResponseFormat> result = null; - * - * try { Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); - * - * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } - * - * User user = validateUserExists.left().value(); // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state org.openecomp.sdc.be.model.Component component = null; - * - * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId; - * - * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); - * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - * - * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - * - * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, - * userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } - * - * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } } - */ - - private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { - String componentTypeForResponse = "SERVICE"; - if (component instanceof Resource) { - componentTypeForResponse = ((Resource) component).getResourceType().name(); - } - return componentTypeForResponse; - } - - /** - * Verify that the artifact members belongs to the component - * - * @param component - * @param artifacts - * @return - */ - private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) { - - if (artifacts == null || true == artifacts.isEmpty()) { - return Either.left(true); - } - - Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); - if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); - if (false == currentArtifacts.containsAll(artifacts)) { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return Either.left(true); - - } - - /** - * verify that the members are component instances of the component - * - * @param component - * @param componentType - * @param groupMembers - * @param memberToscaTypes - * @return - */ - private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, ComponentTypeEnum componentType, String groupName, String groupType, Map<String, String> groupMembers, List<String> memberToscaTypes) { - - if (groupMembers == null || true == groupMembers.isEmpty()) { - return Either.left(true); - } - - if (memberToscaTypes == null || true == memberToscaTypes.isEmpty()) { - return Either.left(true); - } - - List<ComponentInstance> componentInstances = component.getComponentInstances(); - if (componentInstances != null && false == componentInstances.isEmpty()) { - Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); - - Set<String> allCompInstances = compInstUidToCompInstMap.keySet(); - - for (Entry<String, String> groupMember : groupMembers.entrySet()) { - String compName = groupMember.getKey(); - String compUid = groupMember.getValue(); - - if (false == allCompInstances.contains(compUid)) { - /* - * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ] - */ - String componentTypeForResponse = getComponentTypeForResponse(component); - - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse)); - } - } - - // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); - // if (componentOperation instanceof ResourceOperation) { - // ResourceOperation resourceOperation = (ResourceOperation) componentOperation; - // - // for (Entry<String, String> groupMember : groupMembers.entrySet()) { - // - // String componentInstName = groupMember.getKey(); - // String componentInstUid = groupMember.getValue(); - // - // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); - // String componentUid = componentInstance.getComponentUid(); - // List<String> componentToscaNames = new ArrayList<>(); - // TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); - // if (status != TitanOperationStatus.OK) { - // BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - // } - // - // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); - // - // boolean found = false; - // for (String memberToscaType : memberToscaTypes) { - // if (componentToscaNames.contains(memberToscaType)) { - // found = true; - // break; - // } - // } - // if (found == false) { - // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, - // "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); - // /* - // * # %1 - member name # %2 - group name # %3 - group type - // */ - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); - // } else { - // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); - // } - // } - // } else { - // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - // } - - } - - return Either.left(true); - } - - /** - * Update specific group version - * - * @param groupDefinition - * @param inTransaction - * @return - */ - /* - * public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; List<String> groupIdsToUpdateVersion = new - * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); if (updateGroupVersion.isLeft()) - * { result = Either.left(updateGroupVersion.left().value().get(0)); } else { log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); result = Either.right(updateGroupVersion.right().value()); } return - * result; } - */ - - /** - * Update list of groups versions - * - * @param groupsUniqueId - * @param inTransaction - * @return - */ - /* - * public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) { - * - * Either<List<GroupDefinition>, StorageOperationStatus> result = null; - * - * try { - * - * result = groupOperation.updateGroupVersion(groupsUniqueId, true); - * - * return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - */ - - /** - * Update GroupDefinition metadata - * - * @param componentId - * @param user - * @param componentType - * @param updatedGroup - * @param inTransaction - * @return - */ - public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { - - Either<GroupDefinition, ResponseFormat> result = null; - try { - // Validate user exist - Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - // Validate component exist - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); - // validate we can work on component - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId()); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - List<GroupDefinition> currentGroups = component.getGroups(); - if (CollectionUtils.isEmpty(currentGroups)) { - log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); - return result; - } - // Validate groups exists in the component - Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); - if (!currentGroupOpt.isPresent()) { - log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); - return result; - } - GroupDefinition currentGroup = currentGroupOpt.get(); - if ( shouldLock ){ - Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); - if (lockResult.isRight()) { - result = Either.right(lockResult.right().value()); - return result; - } - } - // Validate group type is vfModule - if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType()); - result = Either.right(responseFormat); - return result; - } - result = updateGroupMetadata(component, currentGroup, updatedGroup); - return result; - - } finally { - if (result.isLeft()) { - titanDao.commit(); - } else { - titanDao.rollback(); - } - if( shouldLock ) - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - } - - private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { - String currentGroupName = currentGroup.getName(); - Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); - - if (result.isRight()) { - log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); - } - if (result.isLeft()) { - result = updateGroup(component, currentGroup, currentGroupName); - } - return result; - } - - private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { - Either<GroupDefinition, StorageOperationStatus> handleGroupRes; - Either<GroupDefinition, ResponseFormat> result = null; - if (updatedGroup.getName().equals(currentGroupName)) { - handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } - } else { - StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); - if (deleteStatus != StorageOperationStatus.OK) { - log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); - } - handleGroupRes = groupsOperation.addGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } - } - if (result == null) { - result = Either.left(updatedGroup); - } - return result; - } - - /** - * Validate and Update Group Property - * - * @param componentId - * @param groupUniqueId - * @param user - * @param componentType - * @param groupPropertiesToUpdate - * @param inTransaction - * @return - */ - public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) { - - Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate); - try { - Optional<GroupDefinition> optionalGroupConnectedToVf = null; - GroupDefinition currentGroup = null; - StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); - if (lockResult != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); - } - if (result.isLeft()) { - // VF exist because lock succedded - Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); - optionalGroupConnectedToVf = - // All groups on resource - vf.getGroups().stream(). - // Filter in group sent is part of VF groups - filter(e -> e.getUniqueId().equals(groupUniqueId)). - // Collect - findAny(); - if (!optionalGroupConnectedToVf.isPresent()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); - } - } - - if (result.isLeft()) { - currentGroup = optionalGroupConnectedToVf.get(); - result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); - } - if (result.isLeft()) { - result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); - if (result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); - log.debug("failed to update Vf {}", componentId); - } - } - - } catch (Exception e) { - log.debug("Error in validateAndUpdateGroupProperty {}", e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - return result; - } - - private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { - Map<String, GroupProperty> originalProperties = - // Stream of original properties from group - originalGroup.convertToGroupProperties().stream(). - // Collecting to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - for (GroupProperty gp : groupPropertiesToUpdate) { - if (StringUtils.isEmpty(gp.getValue())) { - gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); - } - } - - } - - private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) { - - Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); - if (ret.isLeft()) { - resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); - } - if (ret.isLeft()) { - // Validate Type Match Value - Optional<StorageOperationStatus> optionalError = - // Stream of group properties - groupPropertiesToUpdate.stream(). - // Validate each and map to returned Strorage status value - map(e -> groupOperation.validateAndUpdatePropertyValue(e)). - // Keep only failed result if there is such - filter(e -> e != StorageOperationStatus.OK). - // collect - findFirst(); - if (optionalError.isPresent()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); - ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - } - if (ret.isLeft()) { - // Validate min max ect... - ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); - } - - return ret; - } - - private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { - - Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - - Map<PropertyNames, String> nameValueMap = new HashMap<>(); - for (GroupProperty gp : groupPropertiesToUpdate) { - // Filter out non special properties which does not have Enum - final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); - if (gpEnum != null) { - nameValueMap.put(gpEnum, gp.getValue()); - } - } - - if (!MapUtils.isEmpty(nameValueMap)) { - - if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { - - Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup); - - Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); - if (eitherValid.isRight()) { - ret = Either.right(eitherValid.right().value()); - } - } - if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { - - Optional<ResponseFormat> optionalError = - // Stream of group Properties - groupPropertiesToUpdate.stream(). - // Filter in only properties that needs text validation - filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). - // validate text properties - map(e -> validateFreeText(e)). - // filter in only errors if exist - filter(e -> e.isRight()). - // map the Either value to the Error - map(e -> e.right().value()) - // collect - .findFirst(); - if (optionalError.isPresent()) { - ret = Either.right(optionalError.get()); - } - - } - } - - return ret; - } - - private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) { - Map<PropertyNames, String> oldValueMap = new HashMap<>(); - PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; - - for (GroupProperty gp : originalGroup.convertToGroupProperties()) { - if (enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)) { - oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); - } - } - if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { - oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); - } - return oldValueMap; - } - - private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { - - Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); - } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); - } else { - Map<String, GroupProperty> namePropertyMap = - // Original Group Properties Stream - originalGroup.convertToGroupProperties().stream(). - // Collect to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - - Optional<GroupProperty> optionalMissingProperty = - // Group Properties to be updated Stream - groupPropertiesToUpdate.stream(). - // Filter in property that is not contained in original if there is such - filter(e -> !namePropertyMap.containsKey(e.getName())). - // collect - findFirst(); - - if (optionalMissingProperty.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); - } else { - Optional<GroupProperty> optionalNonValueChange = - // groups to be updated stream - groupPropertiesToUpdate.stream(). - // filter in only properties with non-value (illegal) change - filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). - // Collect - findFirst(); - if (optionalNonValueChange.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); - - } - } - - } - return ret; - } - - /** - * if groupProperty are the same or if only value is different returns true, otherwise returns false. - * - * @param groupProperty - * @param groupProperty2 - * @return - */ - private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { - // Create 2 duplicates for groupPropery and reset their values - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - try { - GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); - groupPropertyDuplicate.setValue(null); - groupPropertyDuplicate.setSchema(null); - groupPropertyDuplicate.setParentUniqueId(null); - // GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); - GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); - groupProperty2Duplicate.setValue(null); - groupProperty2Duplicate.setSchema(null); - groupProperty2Duplicate.setParentUniqueId(null); - return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()); - } catch (Exception e) { - log.debug("Failed validate group properties. ", e); - return false; - } - } - - /** - * Validate and update GroupDefinition metadata - * - * @param user - * @param currentGroup - * @param groupUpdate - * @return - **/ - private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) { - // Check if to update, and update GroupDefinition name. - Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - // Do not allow to update GroupDefinition version directly. - String versionUpdated = groupUpdate.getVersion(); - String versionCurrent = currentGroup.getVersion(); - if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { - log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); - } - - return Either.left(currentGroup); - } - - /** - * Validate and update GroupDefinition name - * - * @param user - * @param currentGroup - * @param groupUpdate - * @return - */ - private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) { - String nameUpdated = groupUpdate.getName(); - String nameCurrent = currentGroup.getName(); - if (!nameCurrent.equals(nameUpdated)) { - Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true); - if (validatNameResponse.isRight()) { - ResponseFormat errorRespons = validatNameResponse.right().value(); - return Either.right(errorRespons); - } - currentGroup.setName(groupUpdate.getName()); - } - return Either.left(true); - } - - /** - * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part - * MyDesc was changed. - * - * @param currentGroupName - * @param groupUpdateName - * @return - */ - private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) { - try { - // Check if the group name is in old format. - if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) { - log.error("Group name {} is in old format", groupUpdateName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName)); - } - - // Check that name pats 1 and 3 did not changed (only the second - // part can be changed) - // But verify before that the current group format is the new one - if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) { - String[] split1 = currentGroupName.split("\\.\\."); - String currentResourceName = split1[0]; - String currentCounter = split1[2]; - - String[] split2 = groupUpdateName.split("\\.\\."); - String groupUpdateResourceName = split2[0]; - String groupUpdateCounter = split2[2]; - if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes] - if (!currentResourceName.equals(groupUpdateResourceName)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName)); - } - - if (!currentCounter.equals(groupUpdateCounter)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter)); - } - } - - } - - return Either.left(true); - } catch (Exception e) { - log.error("Error valiadting group name", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - - /** - * associate artifacts to a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /* - * public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either<List<GroupDefinition>, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List<GroupDefinition> updatedGroups = new ArrayList<>(); - * - * List<GroupDefinition> componentGroups = component.getGroups(); - * - * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { - * - * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List<String> componentArtifacts = - * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List<String> artifactsToAssociate = groupDefinition.getArtifacts(); - * - * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; } - * - * boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group log.debug("Some of the artifacts already associated to group {}" , - * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } } - * - * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - * - * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } } - */ - - /* - * public Either<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either<List<GroupDefinition>, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List<GroupDefinition> updatedGroups = new ArrayList<>(); - * - * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) { - * - * Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); - * - * if (associateMembersToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } else { updatedGroups.add(associateMembersToGroup.left().value()); } - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } } - */ - - /** - * associate artifacts to a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) { - - Either<GroupDefinitionInfo, ResponseFormat> result = null; - - // Validate user exist - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - org.openecomp.sdc.be.model.Component component = null; - String realComponentId = componentId; - - try { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId); - - if (groupEither.isRight()) { - log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); - return result; - } - GroupDefinition group = groupEither.left().value(); - - Boolean isBase = null;// Constants.IS_BASE; - List<GroupProperty> props = group.convertToGroupProperties(); - if (props != null && !props.isEmpty()) { - Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - // return - // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - - } - } - - List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); - List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>(); - List<String> artifactsIds = group.getArtifacts(); - - Map<String, ArtifactDefinition> deploymentArtifacts = null; - if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { - deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); - } - - if (artifactsIds != null && !artifactsIds.isEmpty()) { - for (String id : artifactsIds) { - if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { - log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); - result = Either.right(responseFormat); - return result; - } - artifactsFromComponent.add(deploymentArtifacts.get(id)); - } - if (!artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); - } - } - - } - GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); - resultInfo.setIsBase(isBase); - if (!artifacts.isEmpty()) - resultInfo.setArtifacts(artifacts); - - result = Either.left(resultInfo); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - } - - private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) { - - Either<GroupDefinition, StorageOperationStatus> result = null; - if (CollectionUtils.isNotEmpty(component.getGroups())) { - Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); - if (foundGroup.isPresent()) { - result = Either.left(foundGroup.get()); - } - } - if (result == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - return result; - } - - /** - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param inTransaction - * @return - */ - private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateGroupsBeforeUpdate(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean inTransaction) { - - Either<org.openecomp.sdc.be.model.Component, ResponseFormat> result; - - // Validate user exist - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, inTransaction); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - String realComponentId = componentId; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); - - // validate we can work on component - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - // Validate groups exists in the component - ResponseFormat validateGroupsInComponent = validateGroupsInComponentByFunc(groups, component, p -> p.getUniqueId()); - if (validateGroupsInComponent != null) { - result = Either.right(validateGroupsInComponent); - return result; - } - - Set<String> artifacts = new HashSet<>(); - groups.forEach(p -> { - if (p.getArtifacts() != null) { - artifacts.addAll(p.getArtifacts()); - } - }); - // validate all artifacts belongs to the component - Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent = verifyArtifactsBelongsToComponent(component, new ArrayList<>(artifacts), UPDATE_GROUP); - if (verifyArtifactsBelongsToComponent.isRight()) { - result = Either.right(verifyArtifactsBelongsToComponent.right().value()); - return result; - } - - return Either.left(component); - } - - /** - * @param groups - * @param component - * @param getByParam - * - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component - * @return - */ - private ResponseFormat validateGroupsInComponentByFunc(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component, Function<GroupDefinition, String> getByParam) { - ResponseFormat result = null; - - List<GroupDefinition> currentGroups = component.getGroups(); - - boolean found = false; - List<String> updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - - List<String> missingGroupNames = updatedGroupsName; - - if (currentGroups != null && false == currentGroups.isEmpty()) { - List<String> currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - - if (currentGroupsName.containsAll(updatedGroupsName)) { - found = true; - } else { - currentGroupsName.removeAll(currentGroupsName); - missingGroupNames = currentGroupsName; - } - } - if (false == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - String listOfGroups = getAsString(missingGroupNames); - result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); - return result; - } - - return null; - } - - public String getAsString(List<String> list) { - - if (list == null || list.isEmpty()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - list.forEach(p -> builder.append(p + ",")); - - String result = builder.toString(); - return result.substring(0, result.length()); - - } - - /** - * dissociate artifacts from a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /* - * public Either<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either<List<GroupDefinition>, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; - * - * try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either<Component, ResponseFormat> validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List<GroupDefinition> updatedGroups = new ArrayList<>(); - * - * List<GroupDefinition> componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { - * - * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List<String> componentArtifacts = - * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List<String> artifactsToDissociate = groupDefinition.getArtifacts(); - * - * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; } - * - * if (artifactsSizeInGroup > 0) { - * - * boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); if (false == containsAll) { // At least one artifact is // not associated to the // group log.debug("Some of the artifacts already dissociated to group {}" , - * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null && - * false == artifactsToDissociate.isEmpty()) { log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, - * componentGroup.getName())); } } } } - * - * Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - * - * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } - * - * } - */ - - /* - * public Either<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) { - * - * Either<List<GroupDefinition>, ResponseFormat> result = null; - * - * List<GroupDefinition> groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try { - * - * if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - * - * if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of - * another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } - * - * User user = validateUserExists.left().value(); - * - * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); - * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - * - * Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - * - * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); - * - * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } - * - * for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) { - * log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } GroupDefinition createdGroup = createGroup.left().value(); groups.add(createdGroup); } } - * - * result = Either.left(groups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } - * - * } - * - * public Either<GroupDefinition, ResponseFormat> createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - * - * Either<GroupDefinition, ResponseFormat> result = null; - * - * log.trace("Going to create group {}" , groupDefinition); - * - * try { - * - * // 3. verify group not already exist List<GroupDefinition> groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { - * - * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - * - * found = existGroupDef != null; } - * - * if (true == found) { String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), - * componentTypeForResponse)); return result; } - * - * // 4. verify type of group exist String groupType = groupDefinition.getType(); if (groupType == null || groupType.isEmpty()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, - * groupDefinition.getName())); return result; } Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); if (getGroupType.isRight()) { StorageOperationStatus status = - * getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); result = - * Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); return result; } else { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } } - * - * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - * - * Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - * - * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; } - * - * // 7. verify the artifacts belongs to the component Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); if (areValidArtifacts.isRight()) { - * ResponseFormat responseFormat = areValidArtifacts.right().value(); result = Either.right(responseFormat); return result; } - * - * NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); - * - * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID); - * - * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID); - * - * // add version groupDefinition.setVersion(INITIAL_VERSION); - * - * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - * - * Either<GroupDefinition, StorageOperationStatus> addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); - * - * if (addGroupToGraph.isRight()) { StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); result = - * Either.right(componentsUtils.getResponseFormat(actionStatus)); log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); } else { GroupDefinition - * groupDefinitionCreated = addGroupToGraph.left().value(); result = Either.left(groupDefinitionCreated); } - * - * return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - * - * public Either<List<GroupDefinition>, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List<GroupDefinition> groups, boolean inTransaction) { List<GroupDefinition> updatedGroups = new ArrayList<>(); - * Either<List<GroupDefinition>, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes; Either<String, ResponseFormat> validateGenerateGroupNameRes; int counter; for - * (GroupDefinition group : groups) { if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { continue; } counter = - * Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); if (validateGenerateGroupNameRes.isRight()) { - * updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; } updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); if - * (updateGroupNameRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); break; } - * updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; } - */ - - private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) { - Either<List<GroupProperty>, ResponseFormat> result; - - Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); - if (eitherUpdate.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } else { - result = Either.left(eitherUpdate.left().value()); - } - return result; - } - - public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) { - Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true); - Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); - for (ArtifactTemplateInfo group : allGroups) { - Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++); - if (validateGenerateGroupNameRes.isRight()) { - validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); - break; - } - group.setGroupName(validateGenerateGroupNameRes.left().value()); - } - return validateGenerateGroupNamesRes; - } - - /** - * Generate module name from resourceName, description and counter - * - * @param resourceSystemName - * @param description - * @param groupCounter - * @return - */ - private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) { - Either<String, ResponseFormat> validateGenerateGroupNameRes; - if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) { - final String fileName = description.replaceAll("\\.\\.", "\\."); - validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter)); - } else { - validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME)); - } - return validateGenerateGroupNameRes; - } - - public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) { - - Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>(); - Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups); - for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { - GroupDefinition curGroup = groupEntry.getValue(); - String groupType = curGroup.getType(); - String groupName = groupEntry.getKey(); - int counter; - String description; - Either<String, ResponseFormat> newGroupNameRes; - if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) { - - if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) { - counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]); - description = curGroup.getDescription(); - } else { - counter = getNextVfModuleNameCounter(updatedNamesGroups); - description = groupName; - } - newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); - if (newGroupNameRes.isRight()) { - log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); - result = Either.right(newGroupNameRes.right().value()); - break; - } - groupName = newGroupNameRes.left().value(); - curGroup.setName(groupName); - } - updatedNamesGroups.put(groupName, curGroup); - } - return result; - } - - public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) { - int counter = 0; - if (groups != null && !groups.isEmpty()) { - counter = getNextVfModuleNameCounter(groups.values()); - } - return counter; - } - - public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) { - int counter = 0; - if (groups != null && !groups.isEmpty()) { - List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) - .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(Collectors.toList()); - counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1; - } - return counter; - } - - public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) { - List<GroupDefinition> updatedGroups = new ArrayList<>(); - Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups); - - for (GroupDefinition group : groups) { - String groupType = group.getType(); - String oldGroupName = group.getName(); - String newGroupName; - Either<String, ResponseFormat> newGroupNameRes; - Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes; - int counter; - if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) { - counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); - newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter); - if (newGroupNameRes.isRight()) { - log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); - result = Either.right(newGroupNameRes.right().value()); - break; - } - newGroupName = newGroupNameRes.left().value(); - group.setName(newGroupName); - - } - updatedGroups.add(group); - - } - - result = Either.left(updatedGroups); - return result; - } - - /* - * public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) { - * - * List<GroupDefinition> generatedGroups = new ArrayList<>(); Either<List<GroupDefinition>, ResponseFormat> result = Either.left(generatedGroups); - * - * try { - * - * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> createGroup = this.createGroup(component, user, componentType, - * groupDefinition, true); if (createGroup.isRight()) { result = Either.right(createGroup.right().value()); return result; } GroupDefinition generatedGroup = createGroup.left().value(); generatedGroups.add(generatedGroup); } } - * - * return result; } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - */ - - public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { - Either<GroupDefinitionInfo, ResponseFormat> result = null; - - // Validate user exist - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - org.openecomp.sdc.be.model.Component component = null; - String realComponentId = componentId; - - try { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreArtifacts(false); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); - - if (findComponentInstanceAndGroupInstanceRes.isRight()) { - log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); - result = Either.right(responseFormat); - return result; - } - - GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); - ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft(); - - Boolean isBase = null;// Constants.IS_BASE; - List<? extends GroupProperty> props = group.convertToGroupInstancesProperties(); - if (props != null && !props.isEmpty()) { - Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - // return - // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - - } - } - - List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); - List<String> artifactsIds = group.getArtifacts(); - if (artifactsIds != null && !artifactsIds.isEmpty()) { - - List<ComponentInstance> instances = component.getComponentInstances(); - if (instances != null) { - Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); - if (findFirst.isPresent()) { - ComponentInstance ci = findFirst.get(); - Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts(); - for (String id : artifactsIds) { - Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - List<String> instArtifactsIds = group.getGroupInstanceArtifacts(); - for (String id : instArtifactsIds) { - Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - } - - } - } - GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); - resultInfo.setIsBase(isBase); - if (!artifacts.isEmpty()) - resultInfo.setArtifacts(artifacts); - - result = Either.left(resultInfo); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - } - - private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { - - Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null; - if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { - Optional<GroupInstance> foundGroup; - Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); - if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { - foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); - if (foundGroup.isPresent()) { - result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); - } - } - } - if (result == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - return result; - } - - private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) { - String value; - if (newValues.containsKey(propertyKey)) { - value = newValues.get(propertyKey); - } else { - value = parentValues.get(propertyKey); - } - return Integer.valueOf(value); - } - - private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) { - return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); - } - - private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) { - - int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); - int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); - int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); - Either<Boolean, ResponseFormat> result = Either.left(true); - - if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) { - if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); - } - } - if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) { - if (latestMaxInstances < latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); - } - - } - if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) { - if (latestMinInstances > latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); - } - - } - return result; - } - - private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) { - - Either<Boolean, ResponseFormat> result; - for (Entry<PropertyNames, String> entry : newValues.entrySet()) { - PropertyNames currPropertyName = entry.getKey(); - if (currPropertyName == PropertyNames.MIN_INSTANCES) { - String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); - String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { - String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); - String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { - String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) { - Either<Boolean, ResponseFormat> result; - final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; - int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); - int minInt = parseIntValue(min.getValue(), min.getKey()); - int maxInt = parseIntValue(max.getValue(), max.getKey()); - if (newValueInt < 0 || minInt < 0 || maxInt < 0) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); - } else if (newValueInt < minInt || newValueInt > maxInt) { - log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - result = Either - .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); - } else { - result = Either.left(true); - } - return result; - } - - private int parseIntValue(String value, PropertyNames propertyName) { - int result; - if (propertyName == PropertyNames.MAX_INSTANCES) { - result = convertIfUnboundMax(value); - } else if (NumberUtils.isNumber(value)) { - result = Integer.parseInt(value); - } else { - result = -1; - } - return result; - } - - /** - * validates received new property values and updates group instance in case of success - * - * @param oldGroupInstance - * @param groupInstanceId - * @param newProperties - * @param inTransaction - * @return - */ - public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) { - - Either<GroupInstance, ResponseFormat> actionResult = null; - Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null; - Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); - if (validateRes.isRight()) { - log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); - actionResult = Either.right(validateRes.right().value()); - } - if (actionResult == null) { - List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value(); - updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); - if (updateGroupInstanceResult.isRight()) { - log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); - } - } - if (actionResult == null) { - actionResult = Either.left(updateGroupInstanceResult.left().value()); - } - return actionResult; - } - - private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { - - Either<Boolean, ResponseFormat> validationRes = null; - Either<List<GroupInstanceProperty>, ResponseFormat> actionResult; - Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class); - List<GroupInstanceProperty> reducedProperties = new ArrayList<>(); - String currPropertyName; - try { - for (GroupInstanceProperty currNewProperty : newProperties) { - currPropertyName = currNewProperty.getName(); - validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); - if (validationRes.isRight()) { - log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); - break; - } - } - if (validationRes == null || validationRes.isLeft()) { - Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class); - Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); - fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); - validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); - } - if (validationRes.isLeft()) { - actionResult = Either.left(reducedProperties); - } else { - actionResult = Either.right(validationRes.right().value()); - } - } catch (Exception e) { - log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return actionResult; - } - - private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) { - PropertyNames[] allPropertyNames = PropertyNames.values(); - for (PropertyNames name : allPropertyNames) { - if (isUpdatable(name)) { - propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); - parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); - } - } - } - - private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { - - Either<Boolean, ResponseFormat> validationRes = null; - String currPropertyName = currNewProperty.getName(); - PropertyNames propertyName = PropertyNames.findName(currPropertyName); - try { - if (currExistingProperty == null) { - log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); - } else if (isUpdatable(propertyName)) { - validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); - if (validationRes.isRight()) { - log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); - } else { - addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); - } - } else { - validateImmutableProperty(currExistingProperty, currNewProperty); - } - if (validationRes == null) { - validationRes = Either.left(true); - } - } catch (Exception e) { - log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); - validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return validationRes; - } - - private boolean isUpdatable(PropertyNames updatablePropertyName) { - return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); - } - - private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - String newValue = newProperty.getValue(); - if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { - newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); - reducedProperties.add(newProperty); - } - if (!isEmptyMinInitialCountValue(propertyName, newValue)) { - newPropertyValues.put(propertyName, newValue); - } - } - - private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { - boolean result = false; - if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { - result = true; - } - return result; - } - - private int convertIfUnboundMax(String value) { - - int result; - if (!NumberUtils.isNumber(value)) { - result = Integer.MAX_VALUE; - } else { - result = Integer.parseInt(value); - } - return result; - } - - private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - Either<Boolean, ResponseFormat> validationRes = null; - String parentValue = existingProperty.getParentValue(); - - newProperty.setParentValue(parentValue); - if (StringUtils.isEmpty(newProperty.getValue())) { - newProperty.setValue(parentValue); - } - if (StringUtils.isEmpty(existingProperty.getValue())) { - existingProperty.setValue(parentValue); - } - StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); - validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (validationRes == null) { - validationRes = Either.left(true); - } - return validationRes; - } - - private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { - if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { - log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); - } - } - - public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) { - - Map<String, GroupDataDefinition> groups = new HashMap<>(); - // Map<String, MapPropertiesDataDefinition> groupsPropertiesMap = new HashMap<>(); - Either<List<GroupDefinition>, ResponseFormat> result = null; - Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - - } - - // handle groups and convert to tosca data - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); - if (handleGroupRes.isRight()) { - result = Either.right(handleGroupRes.right().value()); - break; - } - GroupDefinition handledGroup = handleGroupRes.left().value(); - groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); - - } - } - if (result == null) { - createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - } - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) { - - Either<List<GroupDefinition>, ResponseFormat> result = null; - Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; - List<GroupDataDefinition> groups = new ArrayList<>(); - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - - } - - // handle groups and convert to tosca data - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); - if (handleGroupRes.isRight()) { - result = Either.right(handleGroupRes.right().value()); - break; - } - GroupDefinition handledGroup = handleGroupRes.left().value(); - groups.add(new GroupDataDefinition(handledGroup)); - } - } - if (result == null) { - createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - } - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) { - - Either<List<GroupDefinition>, ResponseFormat> result = null; - Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - /** - * Update specific group version - * - * @param groupDefinition - * @param inTransaction - * @return - */ - public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) { - - Either<List<GroupDefinition>, ResponseFormat> result = null; - Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) { - - Either<GroupDefinition, ResponseFormat> result = null; - - log.trace("Going to create group {}", groupDefinition); - // 3. verify group not already exist - List<GroupDefinition> groups = component.getGroups(); - boolean found = false; - if (groups != null && false == groups.isEmpty()) { - - GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - - found = existGroupDef != null; - } - if (true == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse)); - return result; - } - // 4. verify type of group exist - String groupType = groupDefinition.getType(); - if (groupType == null || groupType.isEmpty()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName())); - return result; - } - Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - if (getGroupType.isRight()) { - StorageOperationStatus status = getGroupType.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - return result; - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - } - // 6. verify the component instances type are allowed according to - // the member types in the group type - GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - - Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - - if (areValidMembers.isRight()) { - ResponseFormat responseFormat = areValidMembers.right().value(); - result = Either.right(responseFormat); - return result; - } - // 7. verify the artifacts belongs to the component - Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); - if (areValidArtifacts.isRight()) { - ResponseFormat responseFormat = areValidArtifacts.right().value(); - result = Either.right(responseFormat); - return result; - } - List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); - - List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); - List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>(); - if (properties != null && false == properties.isEmpty()) { - - if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); - } - - Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - - Either<GroupProperty, TitanOperationStatus> addPropertyResult = null; - int i = 1; - for (GroupProperty prop : properties) { - addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes); - if (addPropertyResult.isRight()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); - } - updatedGroupTypeProperties.add(addPropertyResult.left().value()); - - i++; - } - } - if (groupDefinition.getUniqueId() == null) { - String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName()); - groupDefinition.setUniqueId(uid); - } - groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); - groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); - groupDefinition.setVersion(INITIAL_VERSION); - groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - - return Either.left(groupDefinition); - } - - public Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes) { - - if (prop == null) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - - PropertyDataDefinition propDataDef = prop; - String propertyType = propDataDef.getType(); - String value = groupProperty.getValue(); - - Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef); - if (checkInnerType.isRight()) { - TitanOperationStatus status = checkInnerType.right().value(); - return Either.right(status); - } - - String innerType = checkInnerType.left().value(); - - log.debug("Before validateAndUpdatePropertyValue"); - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); - log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index); - - groupProperty.setUniqueId(uniqueId); - groupProperty.setValue(newValue); - groupProperty.setType(prop.getType()); - groupProperty.setDefaultValue(prop.getDefaultValue()); - groupProperty.setDescription(prop.getDescription()); - groupProperty.setSchema(prop.getSchema()); - groupProperty.setPassword(prop.isPassword()); - groupProperty.setParentUniqueId(prop.getUniqueId()); - - log.debug("Before adding property value to graph {}", groupProperty); - - return Either.left(groupProperty); - } + public static final String GROUP_DELIMITER_REGEX = "\\.\\."; + private static String ADDING_GROUP = "AddingGroup"; + + public static final String INITIAL_VERSION = "1"; + + private static final String CREATE_GROUP = "CreateGroup"; + + private static final String UPDATE_GROUP = "UpdateGroup"; + + private static final String GET_GROUP = "GetGroup"; + + private static final String DELETE_GROUP = "GetGroup"; + + private static final Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class); + + @javax.annotation.Resource + private AccessValidations accessValidations; + + @javax.annotation.Resource + private GroupTypeOperation groupTypeOperation; + + @Autowired + private ArtifactsOperations artifactsOperation; + + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { + String componentTypeForResponse = "SERVICE"; + if (component instanceof Resource) { + componentTypeForResponse = ((Resource) component).getResourceType().name(); + } + return componentTypeForResponse; + } + + /** + * Verify that the artifact members belongs to the component + * + * @param component + * @param artifacts + * @return + */ + private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) { + + if (CollectionUtils.isEmpty(artifacts)) { + return Either.left(true); + } + + Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); + if (MapUtils.isEmpty(deploymentArtifacts)) { + BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(toList()); + log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); + if (!currentArtifacts.containsAll(artifacts)) { + BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return Either.left(true); + + } + + /** + * verify that the members are component instances of the component + * + * @param component + * @param groupMembers + * @param memberToscaTypes + * @return + */ + private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) { + + if (MapUtils.isEmpty(groupMembers)) { + return Either.left(true); + } + + if (CollectionUtils.isEmpty(memberToscaTypes)) { + return Either.left(true); + } + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (CollectionUtils.isNotEmpty(componentInstances)) { + Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); + + Set<String> allCompInstances = compInstUidToCompInstMap.keySet(); + + for (Entry<String, String> groupMember : groupMembers.entrySet()) { + String compName = groupMember.getKey(); + String compUid = groupMember.getValue(); + + if (!allCompInstances.contains(compUid)) { + /* + * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ] + */ + String componentTypeForResponse = getComponentTypeForResponse(component); + + BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse)); + } + } + } + + return Either.left(true); + } + + + + /** + * Update GroupDefinition metadata + * + * @param componentId + * @param user + * @param componentType + * @param updatedGroup + * @param inTransaction + * @return + */ + public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { + + Either<GroupDefinition, ResponseFormat> result = null; + try { + // Validate user exist + Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + // Validate component exist + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); + // validate we can work on component + Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId()); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + List<GroupDefinition> currentGroups = component.getGroups(); + if (CollectionUtils.isEmpty(currentGroups)) { + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + // Validate groups exists in the component + Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); + if (!currentGroupOpt.isPresent()) { + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + GroupDefinition currentGroup = currentGroupOpt.get(); + if ( shouldLock ){ + Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); + if (lockResult.isRight()) { + result = Either.right(lockResult.right().value()); + return result; + } + } + // Validate group type is vfModule + if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) { + log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType()); + result = Either.right(responseFormat); + return result; + } + result = updateGroupMetadata(component, currentGroup, updatedGroup); + return result; + + } finally { + if (result.isLeft()) { + titanDao.commit(); + } else { + titanDao.rollback(); + } + if (shouldLock) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + } + } + + private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { + String currentGroupName = currentGroup.getName(); + Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); + + if (result.isRight()) { + log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + } + if (result.isLeft()) { + result = updateGroup(component, currentGroup, currentGroupName); + } + return result; + } + + private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { + Either<GroupDefinition, StorageOperationStatus> handleGroupRes; + Either<GroupDefinition, ResponseFormat> result = null; + if (updatedGroup.getName().equals(currentGroupName)) { + handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); + if (handleGroupRes.isRight()) { + log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } else { + StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); + if (deleteStatus != StorageOperationStatus.OK) { + log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); + } + handleGroupRes = groupsOperation.addGroup(component, updatedGroup); + if (handleGroupRes.isRight()) { + log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } + if (result == null) { + result = Either.left(updatedGroup); + } + return result; + } + + /** + * Validate and Update Group Property + * + * @param componentId + * @param groupUniqueId + * @param user + * @param componentType + * @param groupPropertiesToUpdate + * @param inTransaction + * @return + */ + public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) { + + Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate); + try { + Optional<GroupDefinition> optionalGroupConnectedToVf = null; + GroupDefinition currentGroup = null; + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); + if (lockResult != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); + } + if (result.isLeft()) { + // VF exist because lock succedded + Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); + optionalGroupConnectedToVf = + // All groups on resource + vf.getGroups().stream(). + // Filter in group sent is part of VF groups + filter(e -> e.getUniqueId().equals(groupUniqueId)). + // Collect + findAny(); + if (!optionalGroupConnectedToVf.isPresent()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); + } + } + + if (result.isLeft()) { + currentGroup = optionalGroupConnectedToVf.get(); + result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); + } + if (result.isLeft()) { + result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); + if (result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); + log.debug("failed to update Vf {}", componentId); + } + } + + } catch (Exception e) { + log.debug("Error in validateAndUpdateGroupProperty {}", e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + return result; + } + + private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { + Map<String, GroupProperty> originalProperties = + // Stream of original properties from group + originalGroup.convertToGroupProperties().stream(). + // Collecting to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + for (GroupProperty gp : groupPropertiesToUpdate) { + if (StringUtils.isEmpty(gp.getValue())) { + gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); + } + } + + } + + private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) { + + Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); + if (ret.isLeft()) { + resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); + } + if (ret.isLeft()) { + // Validate Type Match Value + Optional<StorageOperationStatus> optionalError = + // Stream of group properties + groupPropertiesToUpdate.stream(). + // Validate each and map to returned Strorage status value + map(e -> groupOperation.validateAndUpdatePropertyValue(e)). + // Keep only failed result if there is such + filter(e -> e != StorageOperationStatus.OK). + // collect + findFirst(); + if (optionalError.isPresent()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); + ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + } + if (ret.isLeft()) { + // Validate min max ect... + ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); + } + + return ret; + } + + private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + + Map<PropertyNames, String> nameValueMap = new HashMap<>(); + for (GroupProperty gp : groupPropertiesToUpdate) { + // Filter out non special properties which does not have Enum + final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); + if (gpEnum != null) { + nameValueMap.put(gpEnum, gp.getValue()); + } + } + + if (!MapUtils.isEmpty(nameValueMap)) { + + if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { + + Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup); + + Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); + if (eitherValid.isRight()) { + ret = Either.right(eitherValid.right().value()); + } + } + if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { + + Optional<ResponseFormat> optionalError = + // Stream of group Properties + groupPropertiesToUpdate.stream(). + // Filter in only properties that needs text validation + filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). + // validate text properties + map(e -> validateFreeText(e)). + // filter in only errors if exist + filter(e -> e.isRight()). + // map the Either value to the Error + map(e -> e.right().value()) + // collect + .findFirst(); + if (optionalError.isPresent()) { + ret = Either.right(optionalError.get()); + } + + } + } + + return ret; + } + + private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) { + Map<PropertyNames, String> oldValueMap = new HashMap<>(); + PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; + + for (GroupProperty gp : originalGroup.convertToGroupProperties()) { + if (enumHasValueFilter(gp.getName(), PropertyNames::findName, propertiesToCheck)) { + oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); + } + } + if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { + oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); + } + return oldValueMap; + } + + private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); + } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); + } else { + Map<String, GroupProperty> namePropertyMap = + // Original Group Properties Stream + originalGroup.convertToGroupProperties().stream(). + // Collect to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + + Optional<GroupProperty> optionalMissingProperty = + // Group Properties to be updated Stream + groupPropertiesToUpdate.stream(). + // Filter in property that is not contained in original if there is such + filter(e -> !namePropertyMap.containsKey(e.getName())). + // collect + findFirst(); + + if (optionalMissingProperty.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); + } else { + Optional<GroupProperty> optionalNonValueChange = + // groups to be updated stream + groupPropertiesToUpdate.stream(). + // filter in only properties with non-value (illegal) change + filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). + // Collect + findFirst(); + if (optionalNonValueChange.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); + + } + } + + } + return ret; + } + + /** + * if groupProperty are the same or if only value is different returns true, otherwise returns false. + * + * @param groupProperty + * @param groupProperty2 + * @return + */ + private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { + // Create 2 duplicates for groupPropery and reset their values + try { + GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); + groupPropertyDuplicate.setValue(null); + groupPropertyDuplicate.setSchema(null); + groupPropertyDuplicate.setParentUniqueId(null); + GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); + groupProperty2Duplicate.setValue(null); + groupProperty2Duplicate.setSchema(null); + groupProperty2Duplicate.setParentUniqueId(null); + return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()); + } catch (Exception e) { + log.debug("Failed validate group properties. ", e); + return false; + } + } + + /** + * Validate and update GroupDefinition metadata + * + * @param currentGroup + * @param groupUpdate + * @return + **/ + private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) { + // Check if to update, and update GroupDefinition name. + Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + // Do not allow to update GroupDefinition version directly. + String versionUpdated = groupUpdate.getVersion(); + String versionCurrent = currentGroup.getVersion(); + if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { + log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); + } + + return Either.left(currentGroup); + } + + /** + * Validate and update GroupDefinition name + * + * @param currentGroup + * @param groupUpdate + * @return + */ + private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) { + String nameUpdated = groupUpdate.getName(); + String nameCurrent = currentGroup.getName(); + if (!nameCurrent.equals(nameUpdated)) { + Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true); + if (validatNameResponse.isRight()) { + ResponseFormat errorRespons = validatNameResponse.right().value(); + return Either.right(errorRespons); + } + currentGroup.setName(groupUpdate.getName()); + } + return Either.left(true); + } + + /** + * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part + * MyDesc was changed. + * + * @param currentGroupName + * @param groupUpdateName + * @return + */ + private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) { + try { + // Check if the group name is in old format. + if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) { + log.error("Group name {} is in old format", groupUpdateName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName)); + } + + // Check that name pats 1 and 3 did not changed (only the second + // part can be changed) + // But verify before that the current group format is the new one + if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) { + String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX); + String currentResourceName = split1[0]; + String currentCounter = split1[2]; + + String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX); + String groupUpdateResourceName = split2[0]; + String groupUpdateCounter = split2[2]; + if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes] + if (!currentResourceName.equals(groupUpdateResourceName)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName)); + } + + if (!currentCounter.equals(groupUpdateCounter)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter)); + } + } + + } + + return Either.left(true); + } catch (Exception e) { + log.error("Error valiadting group name", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + + + /** + * associate artifacts to a given group + * + * @param componentId + * @param userId + * @param componentType + * @param inTransaction + * @return + */ + public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) { + + Either<GroupDefinitionInfo, ResponseFormat> result = null; + + // Validate user exist + Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, GET_GROUP, true); + + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + + // Validate component exist + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentId; + + try { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreUsers(false); + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId); + + if (groupEither.isRight()) { + log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); + String componentTypeForResponse = getComponentTypeForResponse(component); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); + return result; + } + GroupDefinition group = groupEither.left().value(); + + Boolean isBase = null; + List<GroupProperty> props = group.convertToGroupProperties(); + if (props != null && !props.isEmpty()) { + Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + } + } + + List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); + List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>(); + List<String> artifactsIds = group.getArtifacts(); + + Map<String, ArtifactDefinition> deploymentArtifacts = null; + if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { + deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); + } + + if (artifactsIds != null && !artifactsIds.isEmpty()) { + for (String id : artifactsIds) { + if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { + log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); + result = Either.right(responseFormat); + return result; + } + artifactsFromComponent.add(deploymentArtifacts.get(id)); + } + if (!artifactsFromComponent.isEmpty()) { + for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { + ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); + artifacts.add(artifactDefinitionInfo); + } + } + + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) { + resultInfo.setArtifacts(artifacts); + } + result = Either.left(resultInfo); + + return result; + + } finally { + + if (!inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + + } + + private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) { + + Either<GroupDefinition, StorageOperationStatus> result = null; + if (CollectionUtils.isNotEmpty(component.getGroups())) { + Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); + if (foundGroup.isPresent()) { + result = Either.left(foundGroup.get()); + } + } + if (result == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + + public String getAsString(List<String> list) { + + if (list == null || list.isEmpty()) { + return ""; + } + StringBuilder builder = new StringBuilder(); + list.forEach(p -> builder.append(p + ",")); + + String result = builder.toString(); + return result.substring(0, result.length()); + + } + + + private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) { + Either<List<GroupProperty>, ResponseFormat> result; + + Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); + if (eitherUpdate.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } else { + result = Either.left(eitherUpdate.left().value()); + } + return result; + } + + public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) { + Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true); + Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); + for (ArtifactTemplateInfo group : allGroups) { + Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++); + if (validateGenerateGroupNameRes.isRight()) { + validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); + break; + } + group.setGroupName(validateGenerateGroupNameRes.left().value()); + } + return validateGenerateGroupNamesRes; + } + + /** + * Generate module name from resourceName, description and counter + * + * @param resourceSystemName + * @param description + * @param groupCounter + * @return + */ + private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) { + Either<String, ResponseFormat> validateGenerateGroupNameRes; + if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) { + final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\."); + validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter)); + } else { + validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME)); + } + return validateGenerateGroupNameRes; + } + + public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) { + + Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>(); + Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups); + for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { + GroupDefinition curGroup = groupEntry.getValue(); + String groupType = curGroup.getType(); + String groupName = groupEntry.getKey(); + int counter; + String description; + Either<String, ResponseFormat> newGroupNameRes; + if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) { + + if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) { + counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]); + description = curGroup.getDescription(); + } else { + counter = getNextVfModuleNameCounter(updatedNamesGroups); + description = groupName; + } + newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); + if (newGroupNameRes.isRight()) { + log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); + result = Either.right(newGroupNameRes.right().value()); + break; + } + groupName = newGroupNameRes.left().value(); + curGroup.setName(groupName); + } + updatedNamesGroups.put(groupName, curGroup); + } + return result; + } + + public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) { + int counter = 0; + if (groups != null && !groups.isEmpty()) { + counter = getNextVfModuleNameCounter(groups.values()); + } + return counter; + } + + public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) { + int counter = 0; + if (groups != null && !groups.isEmpty()) { + List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) + .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList()); + counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1; + } + return counter; + } + + public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) { + List<GroupDefinition> updatedGroups = new ArrayList<>(); + Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups); + + for (GroupDefinition group : groups) { + String groupType = group.getType(); + String oldGroupName = group.getName(); + String newGroupName; + Either<String, ResponseFormat> newGroupNameRes; + int counter; + if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) { + counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); + newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter); + if (newGroupNameRes.isRight()) { + log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); + result = Either.right(newGroupNameRes.right().value()); + break; + } + newGroupName = newGroupNameRes.left().value(); + group.setName(newGroupName); + + } + updatedGroups.add(group); + + } + + result = Either.left(updatedGroups); + return result; + } + + + public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { + Either<GroupDefinitionInfo, ResponseFormat> result = null; + + // Validate user exist + Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); + + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + + // Validate component exist + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentId; + + try { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreArtifacts(false); + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); + + if (findComponentInstanceAndGroupInstanceRes.isRight()) { + log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); + result = Either.right(responseFormat); + return result; + } + + GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); + + Boolean isBase = null; + List<? extends GroupProperty> props = group.convertToGroupInstancesProperties(); + if (props != null && !props.isEmpty()) { + Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + } + } + + List<ArtifactDefinitionInfo> artifacts = new ArrayList<>(); + List<String> artifactsIds = group.getArtifacts(); + if (artifactsIds != null && !artifactsIds.isEmpty()) { + + List<ComponentInstance> instances = component.getComponentInstances(); + if (instances != null) { + Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance ci = findFirst.get(); + Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts(); + for (String id : artifactsIds) { + Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + List<String> instArtifactsIds = group.getGroupInstanceArtifacts(); + for (String id : instArtifactsIds) { + Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + } + + } + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) { + resultInfo.setArtifacts(artifacts); + } + result = Either.left(resultInfo); + + return result; + + } finally { + + if (!inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + } + + private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { + + Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null; + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { + Optional<GroupInstance> foundGroup; + Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); + if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { + foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); + if (foundGroup.isPresent()) { + result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); + } + } + } + if (result == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + + private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) { + String value; + if (newValues.containsKey(propertyKey)) { + value = newValues.get(propertyKey); + } else { + value = parentValues.get(propertyKey); + } + return Integer.valueOf(value); + } + + private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) { + return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); + } + + private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) { + + int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); + int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); + int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); + Either<Boolean, ResponseFormat> result = Either.left(true); + + if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft() + && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft() && + latestMaxInstances < latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && + result.isLeft() && latestMinInstances > latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); + } + return result; + } + + private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) { + + Either<Boolean, ResponseFormat> result; + for (Entry<PropertyNames, String> entry : newValues.entrySet()) { + PropertyNames currPropertyName = entry.getKey(); + if (currPropertyName == PropertyNames.MIN_INSTANCES) { + String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { + String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { + String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) { + Either<Boolean, ResponseFormat> result; + final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; + int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); + int minInt = parseIntValue(min.getValue(), min.getKey()); + int maxInt = parseIntValue(max.getValue(), max.getKey()); + if (newValueInt < 0 || minInt < 0 || maxInt < 0) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); + } else if (newValueInt < minInt || newValueInt > maxInt) { + log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); + result = Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); + } else { + result = Either.left(true); + } + return result; + } + + private int parseIntValue(String value, PropertyNames propertyName) { + int result; + if (propertyName == PropertyNames.MAX_INSTANCES) { + result = convertIfUnboundMax(value); + } else if (NumberUtils.isNumber(value)) { + result = Integer.parseInt(value); + } else { + result = -1; + } + return result; + } + + /** + * validates received new property values and updates group instance in case of success + * + * @param oldGroupInstance + * @param newProperties + * @param inTransaction + * @return + */ + public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) { + + Either<GroupInstance, ResponseFormat> actionResult = null; + Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null; + Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); + if (validateRes.isRight()) { + log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); + actionResult = Either.right(validateRes.right().value()); + } + if (actionResult == null) { + List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value(); + updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); + if (updateGroupInstanceResult.isRight()) { + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); + } + } + if (actionResult == null) { + actionResult = Either.left(updateGroupInstanceResult.left().value()); + } + return actionResult; + } + + private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { + + Either<Boolean, ResponseFormat> validationRes = null; + Either<List<GroupInstanceProperty>, ResponseFormat> actionResult; + Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class); + List<GroupInstanceProperty> reducedProperties = new ArrayList<>(); + String currPropertyName; + try { + for (GroupInstanceProperty currNewProperty : newProperties) { + currPropertyName = currNewProperty.getName(); + validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); + if (validationRes.isRight()) { + log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); + break; + } + } + if (validationRes == null || validationRes.isLeft()) { + Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class); + Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class); + fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); + validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); + } + if (validationRes.isLeft()) { + actionResult = Either.left(reducedProperties); + } else { + actionResult = Either.right(validationRes.right().value()); + } + } catch (Exception e) { + log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return actionResult; + } + + private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) { + PropertyNames[] allPropertyNames = PropertyNames.values(); + for (PropertyNames name : allPropertyNames) { + if (isUpdatable(name)) { + propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); + parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); + } + } + } + + private Either<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + + Either<Boolean, ResponseFormat> validationRes = null; + String currPropertyName = currNewProperty.getName(); + PropertyNames propertyName = PropertyNames.findName(currPropertyName); + try { + if (currExistingProperty == null) { + log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); + } else if (isUpdatable(propertyName)) { + validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); + if (validationRes.isRight()) { + log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); + } else { + addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); + } + } else { + validateImmutableProperty(currExistingProperty, currNewProperty); + } + if (validationRes == null) { + validationRes = Either.left(true); + } + } catch (Exception e) { + log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); + validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return validationRes; + } + + private boolean isUpdatable(PropertyNames updatablePropertyName) { + return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + } + + private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + String newValue = newProperty.getValue(); + if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { + newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); + reducedProperties.add(newProperty); + } + if (!isEmptyMinInitialCountValue(propertyName, newValue)) { + newPropertyValues.put(propertyName, newValue); + } + } + + private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { + boolean result = false; + if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { + result = true; + } + return result; + } + + private int convertIfUnboundMax(String value) { + + int result; + if (!NumberUtils.isNumber(value)) { + result = Integer.MAX_VALUE; + } else { + result = Integer.parseInt(value); + } + return result; + } + + private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + Either<Boolean, ResponseFormat> validationRes = null; + String parentValue = existingProperty.getParentValue(); + + newProperty.setParentValue(parentValue); + if (StringUtils.isEmpty(newProperty.getValue())) { + newProperty.setValue(parentValue); + } + if (StringUtils.isEmpty(existingProperty.getValue())) { + existingProperty.setValue(parentValue); + } + StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); + validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (validationRes == null) { + validationRes = Either.left(true); + } + return validationRes; + } + + private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { + if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { + log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); + } + } + + public GroupDefinition createGroup(String groupType, ComponentTypeEnum componentTypeEnum, String componentId, + String userId) { + + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, CREATE_GROUP); + + validateGroupTypePerComponent(groupType, component); + + GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false) + .left() + .on(se -> onGroupTypeNotFound(component)); + + boolean isFirstGroup = component.getGroups() == null; + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setType(groupType); + + //find next valid counter + int nextCounter = 0; + if (!isFirstGroup) { + nextCounter = getNewGroupCounter(component); + } + String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter); + groupDefinition.setName(name); + + //Add default type properties + List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); + List<GroupProperty> properties = groupTypeProperties.stream() + .map(GroupProperty::new) + .collect(toList()); + groupDefinition.convertFromGroupProperties(properties); + + List<GroupDefinition> gdList; + if (isFirstGroup) { + gdList = createGroups(component, Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + } else { + gdList = addGroups(component, Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + } + return gdList.get(0); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private void validateGroupTypePerComponent(String groupType, Component component) { + String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType(); + if (!component.isTopologyTemplate()) { + throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, + specificType); + } + Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludedGroupTypesMapping(); + + if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) { + Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType); + if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) { + throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType); + } + } + } + + private int getNewGroupCounter(Component component) { + List<String> existingNames = component.getGroups() + .stream() + .map(GroupDataDefinition::getName) + .collect(toList()); + List<String> existingIds = component.getGroups() + .stream() + .map(GroupDataDefinition::getUniqueId) + .collect(toList()); + existingIds.addAll(existingNames); + + return Utils.getNextCounter(existingIds); + } + + public GroupDefinition updateGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId, + String userId, GroupDefinition updatedGroup) { + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, UPDATE_GROUP); + + GroupDefinition existingGroup = findGroupOnComponent(component, groupId) + .left() + .on(se -> onGroupNotFoundInComponentError(component, groupId)); + + String existingGroupName = existingGroup.getName(); + String updatedGroupName = updatedGroup.getName(); + assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component); + existingGroup.setName(updatedGroupName); + + return updateGroup(component, existingGroup, existingGroupName) + .left() + .on(this::onFailedUpdateGroupDBOperation); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) { + if (!ValidationUtils.validateResourceInstanceNameLength(updatedGroupName)) { + throw new ComponentException(ActionStatus.EXCEEDS_LIMIT, "Group Name", ValidationUtils.RSI_NAME_MAX_LENGTH.toString()); + } + if (!ValidationUtils.validateResourceInstanceName(updatedGroupName)) { + throw new ComponentException(ActionStatus.INVALID_VF_MODULE_NAME, updatedGroupName); + } + if (!ComponentValidations.validateNameIsUniqueInComponent(currentGroupName, updatedGroupName, component)) { + throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, "Group", updatedGroupName); + } + } + + public GroupDefinition deleteGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId, + String userId) { + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, DELETE_GROUP); + + GroupDefinition groupDefinition = findGroupOnComponent(component, groupId) + .left() + .on(se -> onGroupNotFoundInComponentError(component, groupId)); + + List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + return gdList.get(0); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private List<GroupDefinition> onFailedGroupDBOperation(ResponseFormat responseFormat) { + titanDao.rollback(); + throw new ComponentException(responseFormat); + } + + private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) { + titanDao.rollback(); + throw new ComponentException(responseFormat); + } + + private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) { + throw new ComponentException(ActionStatus.GROUP_IS_MISSING, groupId, + component.getSystemName(), getComponentTypeForResponse(component)); + } + + private GroupTypeDefinition onGroupTypeNotFound(Component component) { + throw new ComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(), + component.getComponentType().toString()); + } + + private Boolean onFailedToLockComponent(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } + + + public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions) { + + Map<String, GroupDataDefinition> groups = new HashMap<>(); + Either<List<GroupDefinition>, ResponseFormat> result = null; + Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + // handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); + + } + } + if (result == null) { + createGroupsResult = groupsOperation.createGroups(component, groups); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions) { + + Either<List<GroupDefinition>, ResponseFormat> result = null; + Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null; + List<GroupDataDefinition> groups = new ArrayList<>(); + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + // handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.add(new GroupDataDefinition(handledGroup)); + } + } + if (result == null) { + createGroupsResult = groupsOperation.addGroups(component, groups); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) { + + Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult; + + deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(toList())); + if (deleteGroupsResult.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value()))); + } + return Either.left(deleteGroupsResult.left().value()); + } + + /** + * Update specific group version + * + */ + public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions) { + + Either<List<GroupDefinition>, ResponseFormat> result = null; + Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult; + + createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) { + + log.trace("Going to create group {}", groupDefinition); + // 3. verify group not already exist + String groupDefinitionName = groupDefinition.getName(); + if (groupExistsInComponent(groupDefinitionName, component)) { + String componentTypeForResponse = getComponentTypeForResponse(component); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse)); + } + // 4. verify type of group exist + String groupType = groupDefinition.getType(); + if (StringUtils.isEmpty(groupType)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinitionName)); + } + Either<GroupTypeDefinition, StorageOperationStatus> getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); + if (getGroupType.isRight()) { + StorageOperationStatus status = getGroupType.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); + } else { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + // 6. verify the component instances type are allowed according to + // the member types in the group type + GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); + + Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); + + if (areValidMembers.isRight()) { + ResponseFormat responseFormat = areValidMembers.right().value(); + return Either.right(responseFormat); + } + // 7. verify the artifacts belongs to the component + Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); + if (areValidArtifacts.isRight()) { + ResponseFormat responseFormat = areValidArtifacts.right().value(); + return Either.right(responseFormat); + } + List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); + + List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); + List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(properties)) { + if (CollectionUtils.isEmpty(groupTypeProperties)) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); + } + + Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + + Either<GroupProperty, TitanOperationStatus> addPropertyResult; + int i = 1; + for (GroupProperty prop : properties) { + addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType); + if (addPropertyResult.isRight()) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); + } + updatedGroupTypeProperties.add(addPropertyResult.left().value()); + + i++; + } + } + if (groupDefinition.getUniqueId() == null) { + String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName); + groupDefinition.setUniqueId(uid); + } + groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); + groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); + groupDefinition.setVersion(INITIAL_VERSION); + groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + + return Either.left(groupDefinition); + } + + private static boolean groupExistsInComponent(String groupDefinitionName, Component component) { + boolean found = false; + List<GroupDefinition> groups = component.getGroups(); + if (CollectionUtils.isNotEmpty(groups)) { + found = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinitionName)).findFirst().orElse(null) != null; + } + return found; + } + + private Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) { + + if (prop == null) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + + PropertyDataDefinition propDataDef = prop; + String propertyType = propDataDef.getType(); + String value = groupProperty.getValue(); + + Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef); + if (checkInnerType.isRight()) { + TitanOperationStatus status = checkInnerType.right().value(); + return Either.right(status); + } + + String innerType = checkInnerType.left().value(); + + log.debug("Before validateAndUpdatePropertyValue"); + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); + log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (!res) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) + : prop.getUniqueId(); + + groupProperty.setUniqueId(uniqueId); + groupProperty.setValue(newValue); + groupProperty.setType(prop.getType()); + groupProperty.setDefaultValue(prop.getDefaultValue()); + groupProperty.setDescription(prop.getDescription()); + groupProperty.setSchema(prop.getSchema()); + groupProperty.setPassword(prop.isPassword()); + groupProperty.setParentUniqueId(prop.getUniqueId()); + + log.debug("Before adding property value to graph {}", groupProperty); + + return Either.left(groupProperty); + } + + // For old groups we want to leave indexing of property + // For new groups we just need the types + private boolean shouldReconstructUniqueId(String groupType) { + return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java new file mode 100644 index 0000000000..cdd1b30656 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java @@ -0,0 +1,46 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +@Component +public class GroupTypeBusinessLogic { + + private final GroupTypeOperation groupTypeOperation; + private final TitanDao titanDao; + private final UserValidations userValidations; + + public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations) { + this.groupTypeOperation = groupTypeOperation; + this.titanDao = titanDao; + this.userValidations = userValidations; + } + + + public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) { + try { + userValidations.validateUserExists(userId, "get group types", true) + .left() + .on(this::onUserError); + + Set<String> excludeGroupTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping().get(internalComponentType); + return groupTypeOperation.getAllGroupTypes(excludeGroupTypes); + } finally { + titanDao.commit(); + } + } + + private User onUserError(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java index b3448b27ef..5cdb589d2a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; @@ -45,104 +38,152 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @Component("groupTypeImportManager") public class GroupTypeImportManager { - public static void main(String[] args) { - - List<PropertyDefinition> properties = new ArrayList<>(); - PropertyDefinition propertyDefintion = new PropertyDefinition(); - propertyDefintion.setName("aaa"); - properties.add(propertyDefintion); - - List<String> allParentsProps = new ArrayList<>(); - allParentsProps.add("aaa"); - allParentsProps.add("bbb"); - - Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - System.out.println(alreadyExistPropsCollection); - - } - - private static Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class.getName()); - @Resource - private IGroupTypeOperation groupTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private ToscaOperationFacade toscaOperationFacade; - - @Resource - private CommonImportManager commonImportManager; - - public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(String groupTypesYml) { - return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType); - } - - private Either<List<GroupTypeDefinition>, ActionStatus> createGroupTypesFromYml(String groupTypesYml) { - - return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData)); - } - - private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) { - return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()), - groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), null); - } - - private Either<ActionStatus, ResponseFormat> validateGroupType(GroupTypeDefinition groupType) { - Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK); - if (groupType.getMembers() != null) { - if (groupType.getMembers().isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType()); - result = Either.right(responseFormat); - } else { - for (String member : groupType.getMembers()) { - // Verify that such Resource exist - Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); - if (eitherMemberExist.isRight()) { - StorageOperationStatus operationStatus = eitherMemberExist.right().value(); - log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); - ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member); - result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member)); - break; - } - } - - } - } - return result; - } - - private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) { - - GroupTypeDefinition groupType = new GroupTypeDefinition(); - - if (toscaJson != null) { - // Description - final Consumer<String> descriptionSetter = description -> groupType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer<String> derivedFromSetter = derivedFrom -> groupType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> groupType.setProperties(values)); - // Metadata - final Consumer<Map<String, String>> metadataSetter = metadata -> groupType.setMetadata(metadata); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); - // Members - final Consumer<List<String>> membersSetter = members -> groupType.setMembers(members); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), membersSetter); - - groupType.setType(groupTypeName); - - groupType.setHighestVersion(true); - - groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); - } - return groupType; - } + public static void main(String[] args) { + + List<PropertyDefinition> properties = new ArrayList<>(); + PropertyDefinition propertyDefintion = new PropertyDefinition(); + propertyDefintion.setName("aaa"); + properties.add(propertyDefintion); + + List<String> allParentsProps = new ArrayList<>(); + allParentsProps.add("aaa"); + allParentsProps.add("bbb"); + + Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + System.out.println(alreadyExistPropsCollection); + + } + + private static final Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class); + @Resource + private IGroupTypeOperation groupTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private ToscaOperationFacade toscaOperationFacade; + + @Resource + private CommonImportManager commonImportManager; + + public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(String groupTypesYml) { + return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType); + } + + private Either<List<GroupTypeDefinition>, ActionStatus> createGroupTypesFromYml(String groupTypesYml) { + + return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData)); + } + + private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) { + return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()), + groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), groupTypeOperation::upgradeGroupType); + } + + private Either<ActionStatus, ResponseFormat> validateGroupType(GroupTypeDefinition groupType) { + Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK); + if (groupType.getMembers() != null) { + if (groupType.getMembers().isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType()); + result = Either.right(responseFormat); + } else { + for (String member : groupType.getMembers()) { + // Verify that such Resource exist + Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); + if (eitherMemberExist.isRight()) { + StorageOperationStatus operationStatus = eitherMemberExist.right().value(); + log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); + ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member); + result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member)); + break; + } + } + + } + } + return result; + } + + private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) { + + GroupTypeDefinition groupType = new GroupTypeDefinition(); + + if (toscaJson != null) { + // Description + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription); + // Derived From + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), groupType::setDerivedFrom); + // Properties + commonImportManager.setProperties(toscaJson, groupType::setProperties); + // Metadata + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), groupType::setMetadata); + // Capabilities + List<CapabilityTypeDefinition> capabilityTypes = createGroupCapabilityTypes(toscaJson); + groupType.setCapabilityTypes(capabilityTypes); + // Members + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers); + + groupType.setType(groupTypeName); + + groupType.setHighestVersion(true); + + groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); + } + return groupType; + } + + /** + * @param toscaJson + * @return + */ + private List<CapabilityTypeDefinition> createGroupCapabilityTypes(Map<String, Object> toscaJson) { + CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder(); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson); + List<CapabilityTypeDefinition> capabilityTypes; + if (capabilityTypeToscaJsonHolder.isEmpty()) { + capabilityTypes = Collections.emptyList(); + } + else { + capabilityTypes = commonImportManager.createElementTypesFromToscaJsonMap(this::createGroupCapabilityType, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson()); + } + return capabilityTypes; + } + + private class CapabilityTypeToscaJsonHolder { + private Map<String, Object> capabilityTypeToscaJson; + + public Map<String, Object> getCapabilityTypeToscaJson() { + return capabilityTypeToscaJson; + } + + public boolean isEmpty() { + return capabilityTypeToscaJson == null; + } + + public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) { + this.capabilityTypeToscaJson = capabilityTypeToscaJson; + } + } + + private CapabilityTypeDefinition createGroupCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) { + CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); + + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capabilityType::setType); + // Properties + commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties); + + return capabilityType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java deleted file mode 100644 index eff3d39f7f..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java +++ /dev/null @@ -1,526 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.annotation.Resource; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; -import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.util.HealthCheckUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Component("healthCheckBusinessLogic") -public class HealthCheckBusinessLogic { - - protected static String BE_HEALTH_LOG_CONTEXT = "be.healthcheck"; - - private static Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT); - - private static final String BE_HEALTH_CHECK_STR = "beHealthCheck"; - private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s"; - - @Resource - private TitanGenericDao titanGenericDao; - - @Resource - private IEsHealthCheckDao esHealthCheckDao; - - @Resource - private DistributionEngineClusterHealth distributionEngineClusterHealth; - - @Resource - private CassandraHealthCheck cassandraHealthCheck; - - @Autowired - private SwitchoverDetector switchoverDetector; - - private static Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName()); - - private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null; - - public HealthCheckBusinessLogic() { - - } - - private ScheduledFuture<?> scheduledFuture = null; - - ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "BE-Health-Check-Task"); - } - }); - - HealthCheckScheduledTask healthCheckScheduledTask = null; - - @PostConstruct - public void init() { - - prevBeHealthCheckInfos = getBeHealthCheckInfos(); - - log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos); - - healthCheckScheduledTask = new HealthCheckScheduledTask(); - - if (this.scheduledFuture == null) { - this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS); - } - - } - - public boolean isDistributionEngineUp() { - - HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { - return false; - } - return true; - } - - public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() { - - return new ImmutablePair<Boolean, List<HealthCheckInfo>>(getAggregateBeStatus(prevBeHealthCheckInfos), prevBeHealthCheckInfos); - - } - - private Boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) { - - Boolean status = true; - - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && !healthCheckInfo.getHealthCheckComponent().equals(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE)) { - status = false; - break; - } - } - return status; - } - - - private List<HealthCheckInfo> getBeHealthCheckInfos() { - - log.trace("In getBeHealthCheckInfos"); - - List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>(); - - // BE - getBeHealthCheck(healthCheckInfos); - - // Titan - getTitanHealthCheck(healthCheckInfos); - - // Distribution Engine - getDistributionEngineCheck(healthCheckInfos); - - //Cassandra - getCassandraHealthCheck(healthCheckInfos); - - // Amdocs - getAmdocsHealthCheck(healthCheckInfos); - - //DCAE - getDcaeHealthCheck(healthCheckInfos); - - return healthCheckInfos; - } - - private List<HealthCheckInfo> getBeHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - String appVersion = ExternalConfiguration.getAppVersion(); - String description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.UP, appVersion, description)); - return healthCheckInfos; - } - - //Removed from aggregate HC - TDP 293490 - /* private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - - // ES health check and version - HealthCheckStatus healthCheckStatus; - String description; - - try { - healthCheckStatus = esHealthCheckDao.getClusterHealthStatus(); - } catch (Exception e) { - healthCheckStatus = HealthCheckStatus.DOWN; - description = "ES cluster error: " + e.getMessage(); - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description)); - return healthCheckInfos; - } - if (healthCheckStatus.equals(HealthCheckStatus.DOWN)) { - description = "ES cluster is down"; - } else { - description = "OK"; - } - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description)); - return healthCheckInfos; - } - */ - public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - // Titan health check and version - String description; - boolean isTitanUp; - - try { - isTitanUp = titanGenericDao.isGraphOpen(); - } catch (Exception e) { - description = "Titan error: " + e.getMessage(); - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); - return healthCheckInfos; - } - if (isTitanUp) { - description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, description)); - } else { - description = "Titan graph is down"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); - } - return healthCheckInfos; - } - - private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - - String description; - boolean isCassandraUp; - - try { - isCassandraUp = cassandraHealthCheck.getCassandraStatus(); - } catch (Exception e) { - isCassandraUp = false; - description = "Cassandra error: " + e.getMessage(); - } - if (isCassandraUp) { - description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.UP, null, description)); - } else { - description = "Cassandra is down"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.DOWN, null, description)); - } - return healthCheckInfos; - - } - - private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) { - - HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); - - healthCheckInfos.add(healthCheckInfo); - - } - - private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()); - healthCheckInfos.add(beHealthCheckInfo); - return healthCheckInfos; - } - - private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) { - HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl()); - healthCheckInfos.add(beHealthCheckInfo); - return healthCheckInfos; - } - - private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) { - HealthCheckStatus healthCheckStatus; - String description; - String version = null; - List<HealthCheckInfo> componentsInfo = new ArrayList<>(); - - CloseableHttpClient httpClient = getHttpClient(); - - if (healthCheckUrl != null) { - HttpGet httpGet = new HttpGet(healthCheckUrl); - CloseableHttpResponse beResponse; - int beStatus; - try { - beResponse = httpClient.execute(httpGet); - beStatus = beResponse.getStatusLine().getStatusCode(); - - String aggDescription = ""; - - if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) { - HttpEntity entity = beResponse.getEntity(); - String beJsonResponse = EntityUtils.toString(entity); - log.trace("{} Health Check response: {}", componentName, beJsonResponse); - - ObjectMapper mapper = new ObjectMapper(); - Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>(){}); - version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null; - if (healthCheckMap.containsKey("componentsInfo")) { - componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {}); - } - - if (componentsInfo.size() > 0) { - aggDescription = HealthCheckUtil.getAggregateDescription(componentsInfo, null); - } else { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, null)); - } - } else { - log.trace("{} Health Check Response code: {}", componentName, beStatus); - } - - if (beStatus != HttpStatus.SC_OK) { - healthCheckStatus = HealthCheckStatus.DOWN; - description = aggDescription.length() > 0 - ? aggDescription - : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN. - if (componentsInfo.size() == 0) { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - } else { - healthCheckStatus = HealthCheckStatus.UP; - description = "OK"; - } - - } catch (Exception e) { - log.error("{} unexpected response: ", componentName, e); - healthCheckStatus = HealthCheckStatus.DOWN; - description = componentName + " unexpected response: " + e.getMessage(); - if (componentsInfo != null && componentsInfo.size() == 0) { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (IOException e) { - log.error("closing http client has failed" , e); - } - } - } - } else { - healthCheckStatus = HealthCheckStatus.DOWN; - description = componentName + " health check Configuration is missing"; - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - - return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo); - } - - private CloseableHttpClient getHttpClient() { - int timeout = 3000; - RequestConfig.Builder requestBuilder = RequestConfig.custom(); - requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout); - - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setDefaultRequestConfig(requestBuilder.build()); - return builder.build(); - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (healthCheckScheduler != null) { - healthCheckScheduler.shutdown(); - } - - } - - public class HealthCheckScheduledTask implements Runnable { - - List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>(); - - public HealthCheckScheduledTask() { - - } - - @Override - public void run() { - - healthLogger.trace("Executing BE Health Check Task"); - - List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos(); - boolean healthStatus = getAggregateBeStatus(currentBeHealthCheckInfos); - - boolean prevHealthStatus = getAggregateBeStatus(prevBeHealthCheckInfos); - - boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos); - - if (prevHealthStatus != healthStatus || anyStatusChanged) { - log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); - - prevBeHealthCheckInfos = currentBeHealthCheckInfos; - logAlarm(healthStatus); - } - - } - } - - private void logAlarm(boolean prevHealthState) { - if (prevHealthState) { - BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR); - } else { - BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR); - } - } - - private void logAlarm(String componentChangedMsg) { - BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg); - } - - - public String getSiteMode() { - return switchoverDetector.getSiteMode(); - } - - public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) { - - boolean result = false; - - if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) { - - Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); - Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); - - if (currentValues != null && prevValues != null) { - int currentSize = currentValues.size(); - int prevSize = prevValues.size(); - - if (currentSize != prevSize) { - - result = true; //extra/missing component - - Map<String, HealthCheckStatus> notPresent = null; - if (currentValues.keySet().containsAll(prevValues.keySet())) { - notPresent = new HashMap<>(currentValues); - notPresent.keySet().removeAll(prevValues.keySet()); - } else { - notPresent = new HashMap<>(prevValues); - notPresent.keySet().removeAll(currentValues.keySet()); - } - - for (String component : notPresent.keySet()) { - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component))); - } - // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next(); - - } else { - - for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) { - String key = entry.getKey(); - HealthCheckStatus value = entry.getValue(); - - if (!prevValues.containsKey(key)) { - result = true; //component missing - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); - break; - } - - HealthCheckStatus prevHealthCheckStatus = prevValues.get(key); - - if (value != prevHealthCheckStatus) { - result = true; //component status changed - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); - break; - } - } - } - } - - } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) { - result = false; - } else { - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null")); - result = true; - } - - return result; - } - - private String buildOnBoardingHealthCheckUrl() { - - Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); - - if (onboardingConfig != null) { - String protocol = onboardingConfig.getProtocol(); - String host = onboardingConfig.getHost(); - Integer port = onboardingConfig.getPort(); - String uri = onboardingConfig.getHealthCheckUri(); - - return protocol + "://" + host + ":" + port + uri; - } - - log.error("onboarding health check configuration is missing."); - return null; - } - - private String buildDcaeHealthCheckUrl() { - - Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae(); - - if (dcaeConfig != null) { - String protocol = dcaeConfig.getProtocol(); - String host = dcaeConfig.getHost(); - Integer port = dcaeConfig.getPort(); - String uri = dcaeConfig.getHealthCheckUri(); - - return protocol + "://" + host + ":" + port + uri; - } - - log.error("dcae health check configuration is missing."); - return null; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java new file mode 100644 index 0000000000..84df217815 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.common.api.HealthCheckInfo; + +public interface HealthCheckInformer { + + HealthCheckInfo getHealthCheckInfo(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java index 66c1868223..57e6eb54a7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; public interface IDeploymentArtifactTypeConfigGetter { - ArtifactTypeConfig getDeploymentArtifactConfig(); + ArtifactTypeConfig getDeploymentArtifactConfig(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index 01d64f519f..3db76a9398 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -20,20 +20,10 @@ package org.openecomp.sdc.be.components.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Consumer; -import java.util.function.Function; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.commons.lang3.StringEscapeUtils; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; @@ -45,7 +35,6 @@ import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.util.GsonFactory; import org.springframework.beans.factory.config.YamlProcessor; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @@ -54,719 +43,607 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.function.Function; public final class ImportUtils { - private ImportUtils() { - - } - - private static CustomResolver customResolver = new CustomResolver(); - private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader(); - - private static class CustomResolver extends Resolver { - @Override - protected void addImplicitResolvers() { - // avoid implicit resolvers for strings that can be interpreted as boolean values - addImplicitResolver(Tag.STR, EMPTY, ""); - addImplicitResolver(Tag.STR, NULL, null); - addImplicitResolver(Tag.NULL, NULL, "~nN\0"); - addImplicitResolver(Tag.NULL, EMPTY, null); - addImplicitResolver(Tag.INT, INT, "-+0123456789"); - addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); - addImplicitResolver(Tag.YAML, YAML, "!&*"); - } - } - - - private static void buildMap(Map<String, Object> output, Map<String, Object> map) { - for (Entry<String, Object> entry : map.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof Map) { - Map<String, Object> result = new LinkedHashMap<>(); - buildMap(result, (Map) value); - output.put(key, result); - } - else if (value instanceof Collection) { - Map<String, Object> result = new LinkedHashMap<>(); - int i = 0; - for(Object item : (Collection<Object>) value) { - buildMap(result, Collections.singletonMap("[" + (i++) + "]", item)); - } - output.put(key, new ArrayList<>(result.values())); - } - else { - output.put(key, value); - } - } - } - - public static Map<String, Object> loadYamlAsStrictMap(String content){ - Map<String, Object> result = new LinkedHashMap<>(); - Object map = STRICT_MAPPING_YAML_LOADER.load(content); - buildMap(result, (Map<String, Object>)map); - return result; - } - - private static class YamlLoader extends YamlProcessor { - public Yaml getStrictYamlLoader() { - return createYaml(); - } - } - - @SuppressWarnings("unchecked") - public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) { - Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); - return getHeatParameters(heatData, artifactType); - } - - public static class Constants { - - public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0"; - public static final String FIRST_NON_CERTIFIED_VERSION = "0.1"; - public static final String VENDOR_NAME = "ATT (Tosca)"; - public static final String VENDOR_RELEASE = "1.0.0.wd03"; - public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED; - public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; - public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true; - // public static final String ABSTRACT_CATEGORY = "Generic/Abstract"; - public static final String ABSTRACT_CATEGORY_NAME = "Generic"; - public static final String ABSTRACT_SUBCATEGORY = "Abstract"; - public static final String DEFAULT_ICON = "defaulticon"; - public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC"; - public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; - public static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_"; - public static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1"); - public static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar"); - public static final String UI_JSON_PAYLOAD_NAME = "payloadName"; - public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF"; - } - - public enum ResultStatusEnum { - ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME - } - - public enum ToscaElementTypeEnum { - BOOLEAN, STRING, MAP, LIST, ALL - } - - public enum ToscaTagNamesEnum { - DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"), - // Properties - PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"), - // Group Types - MEMBERS("members"), METADATA("metadata"), - // Policy Types - TARGETS("targets"), - // Capabilities - CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"), - // Requirements - REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"), - // Heat env Validation - PARAMETERS("parameters"), - // Import Validations - TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"), - SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"), - // Attributes - ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input"); - - private String elementName; - - private ToscaTagNamesEnum(String elementName) { - this.elementName = elementName; - } - - public String getElementName() { - return elementName; - } - } - - @SuppressWarnings("unchecked") - private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List<Object> returnedList) { - if (elementValue instanceof Map) { - ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList); - } else if (elementValue instanceof List) { - ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList); - } - } - - @SuppressWarnings("unchecked") - private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) { - - if (elementValue instanceof Boolean) { - if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - } - - else if (elementValue instanceof String) { - if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - } else if (elementValue instanceof Map) { - if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList); - - } else if (elementValue instanceof List) { - if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList); - - } - // For Integer, Double etc... - else if (elementType == ToscaElementTypeEnum.ALL) { - if (elementValue != null) { - returnedList.add(String.valueOf(elementValue)); - } - } - } - - private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) { - Iterator<Object> listItr = list.iterator(); - while (listItr.hasNext()) { - Object elementValue = listItr.next(); - handleElementNameNotFound(elementName, elementValue, elementType, returnedList); - } - - } - - public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { - List<Object> foundElements = new ArrayList<>(); - Either<Object, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); - if (foundElements.size() > 0) { - returnedElement = Either.left(foundElements.get(0)); - } - return returnedElement; - - } - - /** - * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br> - * Returns Either element with:<br> - * List with all value if values found<br> - * Or ELEMENT_NOT_FOUND ActionStatus - * - * @param toscaJson - * @param toscaTagName - * @return - */ - public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) { - Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - String skipKey = null; - if (toscaJson.containsKey(elementName)) { - Object elementValue = toscaJson.get(elementName); - handleElementNameFound(elementName, elementType, returnedList, elementValue); - skipKey = elementName; - } - - Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator(); - while (keyValItr.hasNext()) { - Entry<String, Object> keyValEntry = keyValItr.next(); - if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) { - handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList); - } - } - - if (returnedList.size() > 0) { - returnedElement = Either.left(returnedList); - } - - return returnedElement; - } - - @SuppressWarnings("unchecked") - public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { - Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST); - if (findFirstToscaElement.isLeft()) { - returnedElement = Either.left((List<T>) findFirstToscaElement.left().value()); - } - return returnedElement; - - } - - @SuppressWarnings("unchecked") - public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { - Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP); - if (findFirstToscaElement.isLeft()) { - returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value()); - } - return returnedElement; - - } - - public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { - Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING); - if (findFirstToscaElements.isLeft()) { - returnedElement = Either.left((String) findFirstToscaElements.left().value()); - } - return returnedElement; - } - - /** - * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status - * - * @param toscaJson - * @param toscaTagName - * @return - */ - public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { - Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN); - if (findFirstToscaElements.isLeft()) { - returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value())); - } - return returnedElement; - } - - private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) { - Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS); - if (propertyFieldconstraints.isLeft()) { - List<Object> jsonConstraintList = propertyFieldconstraints.left().value(); - - List<PropertyConstraint> constraintList = new ArrayList<>(); - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - for (Object constraintJson : jsonConstraintList) { - PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); - constraintList.add(propertyConstraint); - } - property.setConstraints(constraintList); - } - } - - public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) { - - PropertyDefinition propertyDef = new PropertyDefinition(); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type)); - ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc)); - - Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (findToscaElement.isLeft()) { - String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType()); - propertyDef.setDefaultValue(propertyJsonStringValue); - } - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status)); - ImportUtils.setPropertyScheme(propertyValue, propertyDef); - ImportUtils.setPropertyConstraints(propertyValue, propertyDef); - - return propertyDef; - } - - public static InputDefinition createModuleInput(Map<String, Object> inputValue) { - - InputDefinition inputDef = new InputDefinition(); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc)); - - Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (findToscaElement.isLeft()) { - String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType()); - inputDef.setDefaultValue(propertyJsonStringValue); - } - ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); - ImportUtils.setPropertyScheme(inputValue, inputDef); - ImportUtils.setPropertyConstraints(inputValue, inputDef); - - return inputDef; - } - - public static PropertyDefinition createModuleAttribute(Map<String, Object> attributeMap) { - - PropertyDefinition attributeDef = new PropertyDefinition(); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); - Either<Object, ResultStatusEnum> eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (eitherDefaultValue.isLeft()) { - String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType()); - attributeDef.setDefaultValue(attributeDefaultValue); - } - Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL); - if (eitherValue.isLeft()) { - String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType()); - attributeDef.setValue(attributeValue); - } - ImportUtils.setAttributeScheme(attributeMap, attributeDef); - return attributeDef; - } - - private static void setPropertyFieldStatus(Map<String, Object> propertyValue, PropertyDefinition propertyDef) { - Either<String, ResultStatusEnum> propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); - if (propertyFieldIsStatus.isLeft()) { - propertyDef.setStatus(propertyFieldIsStatus.left().value()); - } - - } - - private static void setAttributeFieldStatus(Map<String, Object> propertyValue, PropertyDefinition propertyDef) { - Either<String, ResultStatusEnum> propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); - if (propertyFieldIsStatus.isLeft()) { - propertyDef.setStatus(propertyFieldIsStatus.left().value()); - } - - } - - private static void setPropertyScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) { - Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue); - if (eitherSchema.isLeft()) { - SchemaDefinition schemaDef = new SchemaDefinition(); - schemaDef.setProperty(eitherSchema.left().value().getProperty()); - propertyDefinition.setSchema(schemaDef); - } - - } - - private static void setAttributeScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) { - Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue); - if (eitherSchema.isLeft()) { - SchemaDefinition schemaDef = new SchemaDefinition(); - schemaDef.setProperty(eitherSchema.left().value().getProperty()); - propertyDefinition.setSchema(schemaDef); - } - - } - - private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) { - Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); - if (propertyFieldEntryScheme.isLeft()) { - if (propertyFieldEntryScheme.left().value() instanceof String) { - String schemaType = (String) propertyFieldEntryScheme.left().value(); - SchemaDefinition schema = new SchemaDefinition(); - PropertyDefinition schemeProperty = new PropertyDefinition(); - schemeProperty.setType(schemaType); - schema.setProperty(schemeProperty); - result = Either.left(schema); - - } else if (propertyFieldEntryScheme.left().value() instanceof Map) { - PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme.left().value()); - SchemaDefinition schema = new SchemaDefinition(); - schema.setProperty(schemeProperty); - result = Either.left(schema); - - } - - } - return result; - } - - private static void setPropertyFieldIsPassword(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldIsPassword = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.IS_PASSWORD); - if (propertyFieldIsPassword.isLeft()) { - dataDefinition.setPassword(Boolean.parseBoolean(propertyFieldIsPassword.left().value())); - } - } - - private static ResultStatusEnum setPropertyFieldDefaultValue(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<Object, ResultStatusEnum> propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - Gson gson = GsonFactory.getGson(); - if (propertyFieldDefaultValue.isLeft()) { - Object defaultValue = propertyFieldDefaultValue.left().value(); - String type = dataDefinition.getType(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type); - // esofer - supporting customized data types. The validation of the - // type will be in the creation of the property. - // if(innerToscaType == null){ - // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE; - // } - // customized data types value is represented as json. - // Also customized data types which are scalar ones, for example, - // data type which derived from integer, their value will be - // represented as json. - if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) { - String jsonObj = null; - if (defaultValue != null) { - jsonObj = gson.toJson(defaultValue); - } - - dataDefinition.setDefaultValue(jsonObj); - } else { - dataDefinition.setDefaultValue(String.valueOf(defaultValue)); - } - - } - - return ResultStatusEnum.OK; - } - - private static ResultStatusEnum setAttributeFieldDefaultValue(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<Object, ResultStatusEnum> propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - Gson gson = GsonFactory.getGson(); - if (propertyFieldDefaultValue.isLeft()) { - Object defaultValue = propertyFieldDefaultValue.left().value(); - String type = dataDefinition.getType(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type); - // esofer - supporting customized data types. The validation of the - // type will be in the creation of the property. - // if(innerToscaType == null){ - // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE; - // } - // customized data types value is represented as json. - // Also customized data types which are scalar ones, for example, - // data type which derived from integer, their value will be - // represented as json. - if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) { - String jsonObj = null; - if (defaultValue != null) { - jsonObj = gson.toJson(defaultValue); - } - - dataDefinition.setDefaultValue(jsonObj); - } else { - dataDefinition.setDefaultValue(String.valueOf(defaultValue)); - } - - } - - return ResultStatusEnum.OK; - } - - public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) { - Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName); - if (fieldStringValue.isLeft()) { - setter.accept(fieldStringValue.left().value()); - } - - } - - private static void setPropertyFieldDescription(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - dataDefinition.setDescription(propertyFieldDescription.left().value()); - } - } - - private static void setPropertyFieldRequired(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED); - if (propertyFieldRequired.isLeft()) { - dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value())); - } - } - - private static void setAttributeFieldType(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - dataDefinition.setType(propertyFieldType.left().value()); - } - } - - private static void setPropertyFieldType(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - dataDefinition.setType(propertyFieldType.left().value()); - } - } - - private static void setAttributeFieldDescription(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { - Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - dataDefinition.setDescription(propertyFieldDescription.left().value()); - } - } - - public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) { - Function<String, PropertyDefinition> elementGenByName = elementName -> createProperties(elementName); - Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleProperty(map); - - return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func); - - } - - public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson) { - Function<String, InputDefinition> elementGenByName = elementName -> createInputs(elementName); - Function<Map<String, Object>, InputDefinition> func = map -> createModuleInput(map); - - return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func); - - } - - public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getAttributes(Map<String, Object> toscaJson) { - Function<String, PropertyDefinition> elementGenByName = elementName -> createAttribute(elementName); - Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleAttribute(map); - - return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); - } - - public static <ElementDefinition> Either<Map<String, ElementDefinition>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementTagName, Function<String, ElementDefinition> elementGenByName, - Function<Map<String, Object>, ElementDefinition> func) { - Either<Map<String, ElementDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); - if (toscaAttributes.isLeft()) { - Map<String, Object> jsonAttributes = toscaAttributes.left().value(); - Map<String, ElementDefinition> moduleAttributes = new HashMap<>(); - Iterator<Entry<String, Object>> propertiesNameValue = jsonAttributes.entrySet().iterator(); - while (propertiesNameValue.hasNext()) { - Entry<String, Object> attributeNameValue = propertiesNameValue.next(); - if (attributeNameValue.getValue() instanceof Map) { - @SuppressWarnings("unchecked") - ElementDefinition attribute = func.apply((Map<String, Object>) attributeNameValue.getValue()); - moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); - } else { - - ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue())); - - moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element); - } - - } - - if (moduleAttributes.size() > 0) { - eitherResult = Either.left(moduleAttributes); - } - - } - return eitherResult; - - } - - private static PropertyDefinition createAttribute(String name) { - PropertyDefinition attribute = new PropertyDefinition(); - - attribute.setName(name); - return attribute; - } - - private static PropertyDefinition createProperties(String name) { - PropertyDefinition property = new PropertyDefinition(); - property.setDefaultValue(name); - property.setName(name); - return property; - } - - private static InputDefinition createInputs(String name) { - InputDefinition input = new InputDefinition(); - - input.setName(name); - return input; - } - - public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) { - - Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS); - if (toscaProperties.isLeft()) { - Map<String, Object> jsonProperties = toscaProperties.left().value(); - List<HeatParameterDefinition> moduleProperties = new ArrayList<>(); - Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator(); - while (propertiesNameValue.hasNext()) { - Entry<String, Object> propertyNameValue = propertiesNameValue.next(); - if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) { - if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - @SuppressWarnings("unchecked") - Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter((Map<String, Object>) propertyNameValue.getValue()); - if (propertyStatus.isRight()) { - return Either.right(propertyStatus.right().value()); - } - HeatParameterDefinition property = propertyStatus.left().value(); - property.setName(String.valueOf(propertyNameValue.getKey())); - moduleProperties.add(property); - } else { - addHeatParamDefinition(moduleProperties, propertyNameValue, true); - } - } else { - addHeatParamDefinition(moduleProperties, propertyNameValue, false); - } - - } - - if (moduleProperties.size() > 0) { - eitherResult = Either.left(moduleProperties); - } - - } - return eitherResult; - - } - - private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue, boolean isJson) { - HeatParameterDefinition property = new HeatParameterDefinition(); - Object value = propertyNameValue.getValue(); - if (value != null) { - property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value))); - } - property.setName(String.valueOf(propertyNameValue.getKey())); - moduleProperties.add(property); - } - - private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) { - HeatParameterDefinition propertyDef = new HeatParameterDefinition(); - String type; - Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - type = propertyFieldType.left().value(); - propertyDef.setType(type); - } else { - return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE); - } - Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - propertyDef.setDescription(propertyFieldDescription.left().value()); - } - - Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (propertyFieldDefaultVal.isLeft()) { - if (propertyFieldDefaultVal.left().value() == null) { - return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE); - } - Object value = propertyFieldDefaultVal.left().value(); - String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)); - propertyDef.setDefaultValue(defaultValue); - propertyDef.setCurrentValue(defaultValue); - } - - return Either.left(propertyDef); - } - - public static String getPropertyJsonStringValue(Object value, String type) { - Gson gson = new Gson(); - if (type == null) { - return null; - } - ToscaPropertyType validType = ToscaPropertyType.isValidType(type); - if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { - return gson.toJson(value); - } - return value.toString(); - } - - /** - * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson - * - * @param toscaJson - * @param elementName - */ - public static void removeElementFromJsonMap(Map<String, Object> toscaJson, String elementName) { - for (Entry<String, Object> entry : toscaJson.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (key.equals(elementName)) { - toscaJson.remove(elementName); - return; - } else if (value instanceof Map) { - removeElementFromJsonMap((Map<String, Object>) value, elementName); - } - } - } + private ImportUtils() { + + } + + private static CustomResolver customResolver = new CustomResolver(); + private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader(); + + private static class CustomResolver extends Resolver { + @Override + protected void addImplicitResolvers() { + // avoid implicit resolvers for strings that can be interpreted as boolean values + addImplicitResolver(Tag.STR, EMPTY, ""); + addImplicitResolver(Tag.STR, NULL, null); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + addImplicitResolver(Tag.INT, INT, "-+0123456789"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.YAML, YAML, "!&*"); + } + } + + + private static void buildMap(Map<String, Object> output, Map<String, Object> map) { + for (Entry<String, Object> entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof Map) { + Map<String, Object> result = new LinkedHashMap<>(); + buildMap(result, (Map) value); + output.put(key, result); + } + else if (value instanceof Collection) { + Map<String, Object> result = new LinkedHashMap<>(); + int i = 0; + for(Object item : (Collection<Object>) value) { + buildMap(result, Collections.singletonMap("[" + (i++) + "]", item)); + } + output.put(key, new ArrayList<>(result.values())); + } + else { + output.put(key, value); + } + } + } + + public static Map<String, Object> loadYamlAsStrictMap(String content){ + Map<String, Object> result = new LinkedHashMap<>(); + Object map = STRICT_MAPPING_YAML_LOADER.load(content); + buildMap(result, (Map<String, Object>)map); + return result; + } + + private static class YamlLoader extends YamlProcessor { + public Yaml getStrictYamlLoader() { + return createYaml(); + } + } + + @SuppressWarnings("unchecked") + public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) { + Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); + return getHeatParameters(heatData, artifactType); + } + + public static class Constants { + + public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0"; + public static final String FIRST_NON_CERTIFIED_VERSION = "0.1"; + public static final String VENDOR_NAME = "ATT (Tosca)"; + public static final String VENDOR_RELEASE = "1.0.0.wd03"; + public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED; + public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; + public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true; + public static final String ABSTRACT_CATEGORY_NAME = "Generic"; + public static final String ABSTRACT_SUBCATEGORY = "Abstract"; + public static final String DEFAULT_ICON = "defaulticon"; + public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC"; + public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; + public static final String UI_JSON_PAYLOAD_NAME = "payloadName"; + public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF"; + } + + public enum ResultStatusEnum { + ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME + } + + public enum ToscaElementTypeEnum { + BOOLEAN, STRING, MAP, LIST, ALL + } + + public enum ToscaTagNamesEnum { + DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"), + // Properties + PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"), + // Group Types + MEMBERS("members"), METADATA("metadata"), + // Policy Types + TARGETS("targets"), + // Capabilities + CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"), + // Requirements + REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"), + // Heat env Validation + PARAMETERS("parameters"), + // Import Validations + TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"), + SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"), + // Attributes + ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input"); + + private String elementName; + + private ToscaTagNamesEnum(String elementName) { + this.elementName = elementName; + } + + public String getElementName() { + return elementName; + } + } + + @SuppressWarnings("unchecked") + private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List<Object> returnedList) { + if (elementValue instanceof Map) { + ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList); + } else if (elementValue instanceof List) { + ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList); + } + } + + @SuppressWarnings("unchecked") + private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) { + + if (elementValue instanceof Boolean) { + if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + } + + else if (elementValue instanceof String) { + if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + } else if (elementValue instanceof Map) { + if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList); + + } else if (elementValue instanceof List) { + if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList); + + } + // For Integer, Double etc... + else if (elementType == ToscaElementTypeEnum.ALL) { + if (elementValue != null) { + returnedList.add(String.valueOf(elementValue)); + } + } + } + + private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) { + Iterator<Object> listItr = list.iterator(); + while (listItr.hasNext()) { + Object elementValue = listItr.next(); + handleElementNameNotFound(elementName, elementValue, elementType, returnedList); + } + + } + + public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { + List<Object> foundElements = new ArrayList<>(); + Either<Object, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); + if (foundElements.size() > 0) { + returnedElement = Either.left(foundElements.get(0)); + } + return returnedElement; + + } + + /** + * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br> + * Returns Either element with:<br> + * List with all value if values found<br> + * Or ELEMENT_NOT_FOUND ActionStatus + * + * @param toscaJson + * @param toscaTagName + * @return + */ + public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) { + Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + String skipKey = null; + if (toscaJson.containsKey(elementName)) { + Object elementValue = toscaJson.get(elementName); + handleElementNameFound(elementName, elementType, returnedList, elementValue); + skipKey = elementName; + } + + Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator(); + while (keyValItr.hasNext()) { + Entry<String, Object> keyValEntry = keyValItr.next(); + if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) { + handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList); + } + } + + if (returnedList.size() > 0) { + returnedElement = Either.left(returnedList); + } + + return returnedElement; + } + + @SuppressWarnings("unchecked") + public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { + Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST); + if (findFirstToscaElement.isLeft()) { + returnedElement = Either.left((List<T>) findFirstToscaElement.left().value()); + } + return returnedElement; + + } + + @SuppressWarnings("unchecked") + public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { + Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP); + if (findFirstToscaElement.isLeft()) { + returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value()); + } + return returnedElement; + + } + + public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { + Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING); + if (findFirstToscaElements.isLeft()) { + returnedElement = Either.left((String) findFirstToscaElements.left().value()); + } + return returnedElement; + } + + /** + * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status + * + * @param toscaJson + * @param toscaTagName + * @return + */ + public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) { + Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN); + if (findFirstToscaElements.isLeft()) { + returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value())); + } + return returnedElement; + } + + private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) { + Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS); + if (propertyFieldconstraints.isLeft()) { + List<Object> jsonConstraintList = propertyFieldconstraints.left().value(); + + List<PropertyConstraint> constraintList = new ArrayList<>(); + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + for (Object constraintJson : jsonConstraintList) { + PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); + constraintList.add(propertyConstraint); + } + property.setConstraints(constraintList); + } + } + + public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) { + + PropertyDefinition propertyDef = new PropertyDefinition(); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type)); + ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc)); + + Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (findToscaElement.isLeft()) { + String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType()); + propertyDef.setDefaultValue(propertyJsonStringValue); + } + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status)); + ImportUtils.setPropertyScheme(propertyValue, propertyDef); + ImportUtils.setPropertyConstraints(propertyValue, propertyDef); + + return propertyDef; + } + + public static InputDefinition createModuleInput(Map<String, Object> inputValue) { + + InputDefinition inputDef = new InputDefinition(); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc)); + + Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (findToscaElement.isLeft()) { + String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType()); + inputDef.setDefaultValue(propertyJsonStringValue); + } + ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); + ImportUtils.setPropertyScheme(inputValue, inputDef); + ImportUtils.setPropertyConstraints(inputValue, inputDef); + + return inputDef; + } + + public static PropertyDefinition createModuleAttribute(Map<String, Object> attributeMap) { + + PropertyDefinition attributeDef = new PropertyDefinition(); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); + Either<Object, ResultStatusEnum> eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (eitherDefaultValue.isLeft()) { + String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType()); + attributeDef.setDefaultValue(attributeDefaultValue); + } + Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL); + if (eitherValue.isLeft()) { + String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType()); + attributeDef.setValue(attributeValue); + } + ImportUtils.setAttributeScheme(attributeMap, attributeDef); + return attributeDef; + } + + private static void setPropertyScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) { + Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue); + if (eitherSchema.isLeft()) { + SchemaDefinition schemaDef = new SchemaDefinition(); + schemaDef.setProperty(eitherSchema.left().value().getProperty()); + propertyDefinition.setSchema(schemaDef); + } + + } + + private static void setAttributeScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) { + Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue); + if (eitherSchema.isLeft()) { + SchemaDefinition schemaDef = new SchemaDefinition(); + schemaDef.setProperty(eitherSchema.left().value().getProperty()); + propertyDefinition.setSchema(schemaDef); + } + + } + + private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) { + Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); + if (propertyFieldEntryScheme.isLeft()) { + if (propertyFieldEntryScheme.left().value() instanceof String) { + String schemaType = (String) propertyFieldEntryScheme.left().value(); + SchemaDefinition schema = new SchemaDefinition(); + PropertyDefinition schemeProperty = new PropertyDefinition(); + schemeProperty.setType(schemaType); + schema.setProperty(schemeProperty); + result = Either.left(schema); + + } else if (propertyFieldEntryScheme.left().value() instanceof Map) { + PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme.left().value()); + SchemaDefinition schema = new SchemaDefinition(); + schema.setProperty(schemeProperty); + result = Either.left(schema); + + } + + } + return result; + } + + public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) { + Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName); + if (fieldStringValue.isLeft()) { + setter.accept(fieldStringValue.left().value()); + } + + } + + private static void setPropertyFieldRequired(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) { + Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED); + if (propertyFieldRequired.isLeft()) { + dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value())); + } + } + + public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) { + Function<String, PropertyDefinition> elementGenByName = elementName -> createProperties(elementName); + Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleProperty(map); + + return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func); + + } + + public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson) { + Function<String, InputDefinition> elementGenByName = elementName -> createInputs(elementName); + Function<Map<String, Object>, InputDefinition> func = map -> createModuleInput(map); + + return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func); + + } + + public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getAttributes(Map<String, Object> toscaJson) { + Function<String, PropertyDefinition> elementGenByName = elementName -> createAttribute(elementName); + Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleAttribute(map); + + return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); + } + + public static <ElementDefinition> Either<Map<String, ElementDefinition>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementTagName, Function<String, ElementDefinition> elementGenByName, + Function<Map<String, Object>, ElementDefinition> func) { + Either<Map<String, ElementDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); + if (toscaAttributes.isLeft()) { + Map<String, Object> jsonAttributes = toscaAttributes.left().value(); + Map<String, ElementDefinition> moduleAttributes = new HashMap<>(); + Iterator<Entry<String, Object>> propertiesNameValue = jsonAttributes.entrySet().iterator(); + while (propertiesNameValue.hasNext()) { + Entry<String, Object> attributeNameValue = propertiesNameValue.next(); + if (attributeNameValue.getValue() instanceof Map) { + @SuppressWarnings("unchecked") + ElementDefinition attribute = func.apply((Map<String, Object>) attributeNameValue.getValue()); + moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); + } else { + + ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue())); + + moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element); + } + + } + + if (moduleAttributes.size() > 0) { + eitherResult = Either.left(moduleAttributes); + } + + } + return eitherResult; + + } + + private static PropertyDefinition createAttribute(String name) { + PropertyDefinition attribute = new PropertyDefinition(); + + attribute.setName(name); + return attribute; + } + + private static PropertyDefinition createProperties(String name) { + PropertyDefinition property = new PropertyDefinition(); + property.setDefaultValue(name); + property.setName(name); + return property; + } + + private static InputDefinition createInputs(String name) { + InputDefinition input = new InputDefinition(); + + input.setName(name); + return input; + } + + public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) { + + Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS); + if (toscaProperties.isLeft()) { + Map<String, Object> jsonProperties = toscaProperties.left().value(); + List<HeatParameterDefinition> moduleProperties = new ArrayList<>(); + Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator(); + while (propertiesNameValue.hasNext()) { + Entry<String, Object> propertyNameValue = propertiesNameValue.next(); + if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) { + if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + @SuppressWarnings("unchecked") + Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter((Map<String, Object>) propertyNameValue.getValue()); + if (propertyStatus.isRight()) { + return Either.right(propertyStatus.right().value()); + } + HeatParameterDefinition property = propertyStatus.left().value(); + property.setName(String.valueOf(propertyNameValue.getKey())); + moduleProperties.add(property); + } else { + addHeatParamDefinition(moduleProperties, propertyNameValue, true); + } + } else { + addHeatParamDefinition(moduleProperties, propertyNameValue, false); + } + + } + + if (moduleProperties.size() > 0) { + eitherResult = Either.left(moduleProperties); + } + + } + return eitherResult; + + } + + private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue, boolean isJson) { + HeatParameterDefinition property = new HeatParameterDefinition(); + Object value = propertyNameValue.getValue(); + if (value != null) { + property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value))); + } + property.setName(String.valueOf(propertyNameValue.getKey())); + moduleProperties.add(property); + } + + private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) { + HeatParameterDefinition propertyDef = new HeatParameterDefinition(); + String type; + Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); + if (propertyFieldType.isLeft()) { + type = propertyFieldType.left().value(); + propertyDef.setType(type); + } else { + return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE); + } + Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); + if (propertyFieldDescription.isLeft()) { + propertyDef.setDescription(propertyFieldDescription.left().value()); + } + + Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (propertyFieldDefaultVal.isLeft()) { + if (propertyFieldDefaultVal.left().value() == null) { + return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE); + } + Object value = propertyFieldDefaultVal.left().value(); + String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)); + propertyDef.setDefaultValue(defaultValue); + propertyDef.setCurrentValue(defaultValue); + } + + return Either.left(propertyDef); + } + + public static String getPropertyJsonStringValue(Object value, String type) { + Gson gson = new Gson(); + if (type == null) { + return null; + } + ToscaPropertyType validType = ToscaPropertyType.isValidType(type); + if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { + return gson.toJson(value); + } + return value.toString(); + } + + /** + * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson + * + * @param toscaJson + * @param elementName + */ + public static void removeElementFromJsonMap(Map<String, Object> toscaJson, String elementName) { + for (Entry<String, Object> entry : toscaJson.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (key.equals(elementName)) { + toscaJson.remove(elementName); + return; + } else if (value instanceof Map) { + removeElementFromJsonMap((Map<String, Object>) value, elementName); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java deleted file mode 100644 index 52dcce9e2e..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -//Pavel -//currently NOT IN USE - there are no informational deployed artifacts after US601880 - -@org.springframework.stereotype.Component("informationDeployedArtifactsBusinessLogic") -public class InformationDeployedArtifactsBusinessLogic { - - /* - * private static Logger log = LoggerFactory.getLogger(InformationDeployedArtifactsBusinessLogic.class. getName()); - * - * @javax.annotation.Resource private ArtifactsBusinessLogic artifactBusinessLogic; - * - * public boolean isInformationDeployedArtifact(ArtifactDefinition artifactInfo) { log.debug("checking if artifact {} is informationalDeployable", artifactInfo.getArtifactName()); boolean informationDeployedArtifact = false; Map<String, - * DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() .getResourceInformationalDeployedArtifacts(); if( resourceInformationalDeployedArtifacts != null && - * resourceInformationalDeployedArtifacts.containsKey(artifactInfo. getArtifactType())){ if( artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL && artifactInfo.checkEsIdExist()){ informationDeployedArtifact = true; - * - * } } String message = (informationDeployedArtifact) ? "artifact {} is informationalDeployable" : "artifact {} is not informationalDeployable"; log.debug(message, artifactInfo.getArtifactName()); return informationDeployedArtifact; } - * - * public Either<Boolean, ResponseFormat> validateArtifact(boolean isCreate, ArtifactDefinition artifactInfo, Component parent, NodeTypeEnum parentType) { - * - * log.debug("checking if informationalDeployable artifact {} is valid ", artifactInfo.getArtifactName()); Wrapper<ResponseFormat> responseFormatWrapper = new Wrapper<ResponseFormat>(); Map<String, DeploymentArtifactTypeConfig> - * resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration(). getResourceInformationalDeployedArtifacts(); - * - * - * artifactBusinessLogic.validateArtifactTypeExists(responseFormatWrapper, artifactInfo); if( responseFormatWrapper.isEmpty() && isCreate ){ artifactBusinessLogic.validateSingleArtifactType(responseFormatWrapper, - * ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parent, parentType); } if( responseFormatWrapper.isEmpty() ){ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - * artifactBusinessLogic.validateFileExtension(responseFormatWrapper, () -> resourceInformationalDeployedArtifacts.get(artifactInfo.getArtifactType() ), artifactInfo, parentType, artifactType); } - * - * if( responseFormatWrapper.isEmpty() ){ validatePayloadContent(responseFormatWrapper, artifactInfo); } - * - * Either<Boolean, ResponseFormat> response; if( responseFormatWrapper.isEmpty() ){ response = Either.left(true); } else{ response = Either.right(responseFormatWrapper.getInnerElement()); } - * - * String message = (response.isLeft()) ? "informationalDeployable artifact {} is valid" : "informationalDeployable artifact {} is not valid"; log.debug(message, artifactInfo.getArtifactName()); return response; } - * - * private void validatePayloadContent(Wrapper<ResponseFormat> responseFormatWrapper, ArtifactDefinition artifactToVerify) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactToVerify.getArtifactType()); if( artifactType == - * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )); - * - * boolean isXmlValid = artifactBusinessLogic.isValidXml(xmlToParse.getBytes()); if( !isXmlValid ){ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus. INVALID_XML, - * artifactToVerify.getArtifactType()); responseFormatWrapper.setInnerElement(responseFormat); log.debug("Xml is not valid for artifact : {}", artifactToVerify.getArtifactName()); } } } - * - * - * - * - * public List<ArtifactDefinition> getInformationalDeployedArtifactsForResourceInstance( ComponentInstance resourceInstance ) { String resourceUid = resourceInstance.getComponentUid(); String resourceName = resourceInstance.getComponentName(); - * return getInformationalDeployedArtifactsForResource(resourceUid, resourceName); } - * - * private List<ArtifactDefinition> getInformationalDeployedArtifactsForResource( String resourceUid, String resourceName) { List<ArtifactDefinition> informationalDeployedArtifacts = new ArrayList<ArtifactDefinition>(); log. - * debug("checking if informationalDeployable artifacts exist for resource {} " , resourceName); Map<String, DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - * .getResourceInformationalDeployedArtifacts(); - * - * - * Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherArtifacts = artifactBusinessLogic.getArtifacts(resourceUid, NodeTypeEnum.Resource, false, ArtifactGroupTypeEnum.INFORMATIONAL); - * - * if( eitherArtifacts.isLeft() && resourceInformationalDeployedArtifacts != null ){ Predicate<ArtifactDefinition> predicate = p -> resourceInformationalDeployedArtifacts.containsKey(p.getArtifactType()) && p.checkEsIdExist() && - * p.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL; informationalDeployedArtifacts = eitherArtifacts.left().value().values().stream().filter( predicate ).collect(Collectors.toList()); } - * - * if( informationalDeployedArtifacts.isEmpty() ){ log.debug("no informationalDeployable artifacts exist for resource {} ", resourceName); } else{ log. debug("informationalDeployable artifacts found for resource {} are :{}", resourceName, - * informationalDeployedArtifacts.toString()); } - * - * - * return informationalDeployedArtifacts; } - * - * public List<ArtifactDefinition> getAllDeployableArtifacts( Resource resource ){ List<ArtifactDefinition> merged = new ArrayList<ArtifactDefinition>(); - * - * List<ArtifactDefinition> deploymentArtifacts = artifactBusinessLogic.getDeploymentArtifacts(resource, NodeTypeEnum.Resource); merged.addAll(deploymentArtifacts); - * - * List<ArtifactDefinition> informationalDeployedArtifactsForResource = getInformationalDeployedArtifactsForResource( resource.getUniqueId(), resource.getName()); merged.addAll(informationalDeployedArtifactsForResource); - * - * return merged; } - */ -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index a9e7f0b34b..7b51e92ba2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -20,28 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.stream.Collectors; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.json.simple.JSONObject; +import fj.data.Either; +import org.openecomp.sdc.be.components.property.PropertyDecelerationOrchestrator; import org.openecomp.sdc.be.components.validation.ComponentValidations; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -49,1415 +33,651 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; - -import com.google.gson.Gson; -import fj.data.Either; -import jline.internal.Log; +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_INPUT = "CreateInput"; - private static final String UPDATE_INPUT = "UpdateInput"; - - private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName()); - - private static final String GET_INPUT = "get_input"; - - private static final short LOOP_PROTECTION_LEVEL = 10 ; - - private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty"; - private Gson gson = new Gson(); - - - /** - * associate inputs to a given component with paging - * - * @param componentId - * @param userId - * @param fromId - * @param amount - * @return - */ - public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false); - - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreInputs(false); - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - List<InputDefinition> inputs = component.getInputs(); - - return Either.left(inputs); - - } - - public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false); - - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreComponentInstancesInputs(false); - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - - if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){ - ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; - log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap()); - return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList())); - } - - /** - * associate properties to a given component instance input - * - * @param instanceId - * @param userId - * @param inputId - * @return - */ - - public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - String parentId = componentId; - org.openecomp.sdc.be.model.Component component = null; - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - - if(!instanceId.equals(inputId)){ - - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny(); - if(ciOp.isPresent()){ - parentId = ciOp.get().getComponentUid(); - } - - } - - filters.setIgnoreInputs(false); - - filters.setIgnoreComponentInstancesProperties(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreProperties(false); - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - - Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - return Either.left(getComponentInstancePropertiesByInputId(component, inputId)); - - } - - public Either<InputDefinition, ResponseFormat> updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) { - - Either<InputDefinition, ResponseFormat> result = null; - org.openecomp.sdc.be.model.Component component = null; - - - try { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false); - - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreUsers(false); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); - return result; - } - } - - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - - Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; - log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - InputDefinition currentInput = op.get(); - - String innerType = null; - String propertyType = currentInput.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = currentInput.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value()); - - String newValue = currentInput.getDefaultValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - currentInput.setDefaultValue(newValue); - currentInput.setOwnerId(userId); - - Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currentInput); - - if(status.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); - return result; - } - - - result = Either.left(status.left().value()); - - return result; - - - }finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - - } - - public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - String parentId = componentId; - org.openecomp.sdc.be.model.Component component = null; - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreProperties(false); - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - - Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - return Either.left(getComponentInstanceInputsByInputId(component, inputId)); - - } - - public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { - - Either<List<InputDefinition>, ResponseFormat> result = null; - org.openecomp.sdc.be.model.Component component = null; - - Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap = new HashMap<>(); - Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap = new HashMap<>(); - Map<String, InputDefinition> inputsToCreate = new HashMap<>(); - - try { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); - - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreComponentInstancesInputs(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreComponentInstancesProperties(false); - componentParametersView.setIgnoreUsers(false); + private static final String CREATE_INPUT = "CreateInput"; + private static final String UPDATE_INPUT = "UpdateInput"; - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + private static final Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + @Inject + private PropertyDecelerationOrchestrator propertyDecelerationOrchestrator; + @Inject + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - if (shouldLockComp) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); - return result; - } - } + /** + * associate inputs to a given component with paging + * + * @param userId + * @param componentId + * @return + */ + public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) { - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - Map<String, org.openecomp.sdc.be.model.Component> origComponentMap = new HashMap<>(); - - - ////////////////////////////////////////////////////////////////////////////////////////////////////// + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false); - List<InputDefinition> resList = new ArrayList<InputDefinition>(); - Map<String, List<ComponentInstancePropInput>> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap(); - List<ComponentInstance> ciList = component.getComponentInstances(); - if (newInputsMap != null && !newInputsMap.isEmpty()) { - - result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsMap, true); - - if (result.isRight()) { - log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value()); - return result; - } - resList = result.left().value(); - - + if (resp.isRight()) { + return Either.right(resp.right().value()); + } - } - Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties(); - if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) { + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); - result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsPropsMap, false); + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); - if (result.isRight()) { - log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value()); - return result; - } - resList = result.left().value(); + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + List<InputDefinition> inputs = component.getInputs(); - } + return Either.left(inputs); - assignOwnerIdToInputs(userId, inputsToCreate); + } - Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId()); - if(assotiateInputsEither.isRight()){ - log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } + public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId()); - if(assotiatePropsEither.isRight()){ - log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } - - Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(component, inputsValueToCreateMap); - if(addciInputsEither.isRight()){ - log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } - - - - - result = Either.left(resList); - return result; - /////////////////////////////////////////////////////////////////////////////////////////// - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) { - inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId)); - } - - private StorageOperationStatus addInputsToComponent(String componentId, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap, Map<String, DataTypeDefinition> allDataTypes, List<InputDefinition> resList, int index, - String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) { - - - Either<List<InputDefinition>, ResponseFormat> result; - String innerType = null; - InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get(); - String serviceInputName = compInstname + "_" + input.getName(); - input.setName(serviceInputName); - - JSONObject jobject = new JSONObject(); - jobject.put(GET_INPUT, input.getName()); - - ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null); - - Either<String, StorageOperationStatus> validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - - return validatevalueEiter.right().value(); - } - - String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++); - inputValue.setUniqueId(uniqueId); - inputValue.setValue(validatevalueEiter.left().value()); - - - input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName())); - input.setSchema(oldInput.getSchema()); - input.setDefaultValue(oldInput.getDefaultValue()); - input.setConstraints(oldInput.getConstraints()); - input.setDescription(oldInput.getDescription()); - input.setHidden(oldInput.isHidden()); - input.setImmutable(oldInput.isImmutable()); - input.setDefinition(oldInput.isDefinition()); - input.setRequired(oldInput.isRequired()); - input.setOwnerId(null); - input.setParentUniqueId(null); - input.setInstanceUniqueId(compInstId); - inputsToCreate.put(input.getName(), input); - - - - List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputId(input.getUniqueId()); - getInputValueDataDefinition.setInputName(input.getName()); - getInputValues.add(getInputValueDataDefinition); - inputValue.setGetInputValues(getInputValues); - - List<ComponentInstanceInput> inputsValueToCreate = null; - - if(inputsValueToCreateMap.containsKey(compInstId)){ - inputsValueToCreate = inputsValueToCreateMap.get(compInstId); - }else{ - inputsValueToCreate = new ArrayList<>(); - } - inputsValueToCreate.add(inputValue); - inputsValueToCreateMap.put(compInstId, inputsValueToCreate); - - - inputsValueToCreate.add(inputValue); - List<ComponentInstanceInput> inputsValue = input.getInputs(); - if(inputsValue == null) - inputsValue = new ArrayList<>(); - inputsValue.add(inputValue); - input.setInputs(inputsValue); + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false); - resList.add(input); - return StorageOperationStatus.OK; - } - - public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp, boolean inTransaction) { - - Either<List<InputDefinition>, ResponseFormat> result = null; - - org.openecomp.sdc.be.model.Component component = null; - try { - - if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) { - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_INPUT, true); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - - Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - Map<String, InputDefinition> inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o)); - - result = createInputsInGraph(inputs, component); - } - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) { - - List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList()); - Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList); - List<InputDefinition> resourceProperties = component.getInputs(); - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - - for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) { - String inputName = inputDefinition.getKey(); - inputDefinition.getValue().setName(inputName); - - Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); - if(preparedInputEither.isRight()){ - return Either.right(preparedInputEither.right().value()); - } - - } - if (resourceProperties != null) { - Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); - Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); - if(mergeEither.isRight()){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); - } - inputs = mergeEither.left().value(); - } - - Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); - if(assotiateInputsEither.isRight()){ - log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - } - result = Either.left(assotiateInputsEither.left().value()); - - return result; - } - - - /* Mutates the object - * Tail recurse -> traverse the tosca elements and remove nested empty map properties - * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected - * - * @param toscaElement - expected map of tosca values - * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map. - **/ - private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){ - //region - Stop if map is empty - if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map)) - return toscaElement; - //endregion - //region - Remove empty map entries & return null iff empty map - if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) { - Object ret; - Set<Object> keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException - for( Object key : ((Map)toscaElement).keySet() ) { - Object value = ((Map) toscaElement).get(key); - ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel ); - if ( ret == null ) - keysToRemove.add(key); - } - Collection set = ((Map) toscaElement).keySet(); - if (CollectionUtils.isNotEmpty(set)) - set.removeAll(keysToRemove); - - if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check - return null; - } - //endregion - else - return null; - return toscaElement; - } - - //@returns true iff map nested maps are all empty - //ignores other collection objects - private boolean isEmptyNestedMap(Object element){ - boolean isEmpty = true; - if (element != null){ - if ( element instanceof Map ){ - if (MapUtils.isEmpty((Map)element)) - isEmpty = true; - else - { - for( Object key : ((Map)(element)).keySet() ){ - Object value = ((Map)(element)).get(key); - isEmpty &= isEmptyNestedMap( value ); - } - } - } else { - isEmpty = false; - } - } - return isEmpty; - } - - public Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){ - if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){ - if (deepClone){ - if (!(mappedToscaTemplate instanceof HashMap)) - return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() ); - else - mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone(); - } - return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , InputsBusinessLogic.LOOP_PROTECTION_LEVEL ) ); - } - else { - log.debug("mappedToscaTemplate is empty "); - return Either.right("mappedToscaTemplate is empty "); - } - } - - - - /** - * Delete input from service - * - * @param componentType - * @param inputId - * @param component - * @param user - * - * @return - */ - public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId) { - - Either<InputDefinition, ResponseFormat> deleteEither = null; - if (log.isDebugEnabled()) - log.debug("Going to delete input id: {}", inputId); - - // Validate user (exists) - Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true); - if (userEither.isRight()) { - deleteEither = Either.right(userEither.right().value()); - return deleteEither; - } - - // Get component using componentType, componentId - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreComponentInstancesInputs(false); - componentParametersView.setIgnoreComponentInstancesProperties(false); - componentParametersView.setIgnoreUsers(false); - - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - if (componentEither.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); - return deleteEither; - } - org.openecomp.sdc.be.model.Component component = componentEither.left().value(); - - // Validate inputId is child of the component - Optional<InputDefinition> optionalInput = component.getInputs().stream(). - // filter by ID - filter(input -> input.getUniqueId().equals(inputId)). - // Get the input - findAny(); - if (!optionalInput.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); - } - - InputDefinition inputForDelete = optionalInput.get(); - - // Lock component - Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput"); - if (lockResultEither.isRight()) { - ResponseFormat responseFormat = lockResultEither.right().value(); - deleteEither = Either.right(responseFormat); - return deleteEither; - } - - // Delete input operations - try { - StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId); - - if(inputsValue != null && !inputsValue.isEmpty()){ - for(ComponentInstanceInput inputValue: inputsValue){ - String compInstId = inputValue.getComponentInstanceId(); - prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath()); - - status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - } - - - } - - // US848813 delete service input that relates to VL / CP property - - List<ComponentInstanceProperty> propertiesValue = getComponentInstancePropertiesByInputId(component, inputId); - if(propertiesValue != null && !propertiesValue.isEmpty()){ - //propertyList = propertyValueStatus.left().value(); - for(ComponentInstanceProperty propertyValue: propertiesValue){ - - String compInstId = propertyValue.getComponentInstanceId(); - prepareValueBeforeDelete(compInstId, inputForDelete, propertyValue, propertyValue.getPath()); - - status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - } - } - - - deleteEither = Either.left(inputForDelete); - return deleteEither; - } finally { - if (deleteEither == null || deleteEither.isRight()) { - log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - titanDao.rollback(); - } else { - log.debug("Component id: {} delete input id: {} success", componentId, inputId); - titanDao.commit(); - } - unlockComponent(deleteEither, component); - } - } - - private Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(String compInstId, InputDefinition inputForDelete, PropertyDefinition inputValue, List<String> pathOfComponentInstances) { - Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete); - String value = inputValue.getValue(); - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value); - - resetInputName(mappedToscaTemplate, inputForDelete.getName()); - - value = ""; - if(!mappedToscaTemplate.isEmpty()){ - Either result = cleanNestedMap(mappedToscaTemplate , true); - Map modifiedMappedToscaTemplate = mappedToscaTemplate; - if (result.isLeft()) - modifiedMappedToscaTemplate = (Map)result.left().value(); - else - Log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation - value = gson.toJson(modifiedMappedToscaTemplate); - } - inputValue.setValue(value); - - - List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues(); - if(getInputsValues != null && !getInputsValues.isEmpty()){ - Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny(); - if(op.isPresent()){ - getInputsValues.remove(op.get()); - } - } - inputValue.setGetInputValues(getInputsValues); - - Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue()); - if (findDefaultValue.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); - return deleteEither; - - } - String defaultValue = findDefaultValue.left().value(); - inputValue.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - return deleteEither; - } - - private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) { - - - // validate input default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - // convert property - ToscaPropertyType type = getType(newInputDefinition.getType()); - if (type != null) { - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - if (newInputDefinition != null) { - SchemaDefinition schema = newInputDefinition.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (prop != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newInputDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); - newInputDefinition.setDefaultValue(convertedValue); - } - } - } - return Either.left(newInputDefinition); - } - - public boolean isInputExist(List<InputDefinition> inputs, String resourceUid, String inputName) { - - if (inputs == null) { - return false; - } - - for (InputDefinition propertyDefinition : inputs) { - String parentUniqueId = propertyDefinition.getParentUniqueId(); - String name = propertyDefinition.getName(); - - if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) { - return true; - } - } - - return false; - - } - - - public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { - Either<InputDefinition, ResponseFormat> result = null; - try { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = null; - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreComponentInstancesProperties(false); - filters.setIgnoreProperties(false); - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - InputDefinition resObj = op.get(); - - List<ComponentInstanceInput> inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ; - - resObj.setInputs(inputCIInput); - - - List<ComponentInstanceProperty> inputProps = getComponentInstancePropertiesByInputId(component, inputId) ; - - resObj.setProperties(inputProps); - - - result = Either.left(resObj); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - } - - private List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ - List<ComponentInstanceProperty> resList = new ArrayList<>(); - Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties(); - if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){ - ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() { - @Override - public void accept(String s, List<ComponentInstanceProperty> ciPropList) { - String ciName = ""; - Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); - if(ciOp.isPresent()) - ciName = ciOp.get().getName(); - if (ciPropList != null && !ciPropList.isEmpty()) { - for(ComponentInstanceProperty prop: ciPropList){ - List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } - - } - } - } - }); - } - return resList; - - } - - private List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ - List<ComponentInstanceInput> resList = new ArrayList<>(); - Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs(); - if(ciInputsMap != null && !ciInputsMap.isEmpty()){ - ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() { - @Override - public void accept(String s, List<ComponentInstanceInput> ciPropList) { - String ciName = ""; - Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); - if(ciOp.isPresent()) - ciName = ciOp.get().getName(); - if (ciPropList != null && !ciPropList.isEmpty()) { - for(ComponentInstanceInput prop: ciPropList){ - List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } - - } - } - } - }); - } - return resList; - - } - - private Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getOriginComponent(ComponentInstance ci, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap){ - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> result = null; - String compInstname = ci.getNormalizedName(); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - org.openecomp.sdc.be.model.Component origComponent = null; - if(!origComponentMap.containsKey(ci.getComponentUid())){ - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView); - - if (componentFound.isRight()) { - result = Either.right(componentFound.right().value()); - return result; - } - origComponent = componentFound.left().value(); - origComponentMap.put(origComponent.getUniqueId(), origComponent); - }else{ - origComponent = origComponentMap.get(ci.getComponentUid()); - } - result = Either.left(origComponent); - return result; - } - - - - private Either<List<InputDefinition>, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap, boolean isInputValue) { - List<ComponentInstance> ciList = component.getComponentInstances(); - String componentId = component.getUniqueId(); - for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) { - String compInstId = entry.getKey(); - List<ComponentInstanceProperty> propertiesToCreate = null; - if(propertiesToCreateMap.containsKey(compInstId)){ - propertiesToCreate = propertiesToCreateMap.get(compInstId); - }else{ - propertiesToCreate = new ArrayList<>(); - } - - List<ComponentInstanceInput> inputsValueToCreate = null; - if(propertiesToCreateMap.containsKey(compInstId)){ - inputsValueToCreate = inputsValueToCreateMap.get(compInstId); - }else{ - inputsValueToCreate = new ArrayList<>(); - } - - List<ComponentInstancePropInput> properties = entry.getValue(); - - Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny(); - if(!op.isPresent()){ - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - log.debug("Failed to find component instance {} under component {}", compInstId, componentId); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - ComponentInstance ci = op.get(); - String compInstname = ci.getNormalizedName(); - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap); - if(origComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value()); - log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value(); - - - //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); - - String inputName = compInstname; - - if (properties != null && !properties.isEmpty()) { - for (ComponentInstancePropInput propInput : properties) { - propInput.setOwnerId(null); - propInput.setParentUniqueId(null); - - Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(component, ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, inputName, propInput, isInputValue); - - if (createInputRes.isRight()) { - log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value()))); - - } - - resList.add(createInputRes.left().value()); - - } - if(! isInputValue){ - propertiesToCreateMap.put(compInstId, propertiesToCreate); - } - else{ - inputsValueToCreateMap.put(compInstId, inputsValueToCreate); - } - } - - } - return Either.left(resList); - } - - private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance ci, Map<String, InputDefinition> inputsToCreate, List<ComponentInstanceProperty> propertiesToCreate, List<ComponentInstanceInput> inputsValueToCreate, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) { - String propertiesName = propInput.getPropertiesName() ; - PropertyDefinition selectedProp = propInput.getInput(); - String[] parsedPropNames = propInput.getParsedPropNames(); - - if(parsedPropNames != null){ - for(String str: parsedPropNames){ - inputName += "_" + str; - } - } else { - inputName += "_" + propInput.getName(); - } - - InputDefinition input = null; - PropertyDefinition prop = propInput; - - if(CollectionUtils.isNotEmpty(propertiesToCreate) && !isInputValue){ - Optional<ComponentInstanceProperty> propOpt = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst(); - if(propOpt.isPresent()){ - prop = propOpt.get(); - } - }else{ - if(CollectionUtils.isNotEmpty(inputsValueToCreate) && isInputValue){ - Optional<ComponentInstanceInput> propOpt = inputsValueToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst(); - if(propOpt.isPresent()){ - prop = propOpt.get(); - } - } - } - - boolean complexProperty = false; - if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ - complexProperty = true; - input = new InputDefinition(selectedProp); - }else{ - input = new InputDefinition(prop); - input.setName(inputName + "_" + prop.getName()); - - } - input.setDefaultValue(prop.getValue()); - input.setName(inputName); - input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName())); - input.setInputPath(propertiesName); - input.setInstanceUniqueId(ci.getUniqueId()); - input.setPropertyId(propInput.getUniqueId()); - - JSONObject jobject = new JSONObject(); - - - if(prop.getValue() == null || prop.getValue().isEmpty()){ - if(complexProperty){ - - jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); - prop.setValue(jobject.toJSONString()); - - }else{ - - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - } - - }else{ - - String value = prop.getValue(); - Object objValue = new Yaml().load(value); - if( objValue instanceof Map || objValue instanceof List ){ - if(!complexProperty){ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - - }else{ - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue; - createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); - - String json = gson.toJson(mappedToscaTemplate); - prop.setValue(json); - - } - - }else{ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - } - - } - - ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(ci.getUniqueId()); - ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(ci.getName()); - - if(CollectionUtils.isEmpty(prop.getGetInputValues())){ - prop.setGetInputValues(new ArrayList<>()); - } - List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues(); - - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputId(input.getUniqueId()); - getInputValueDataDefinition.setInputName(input.getName()); - getInputValues.add(getInputValueDataDefinition); - - if(!isInputValue){ - if(!propertiesToCreate.contains(prop)){ - propertiesToCreate.add((ComponentInstanceProperty)prop); - } - - inputsToCreate.put(input.getName(), input); - List<ComponentInstanceProperty> propertiesList = input.getProperties(); - if(propertiesList == null) - propertiesList = new ArrayList<>(); // adding the property with the new value for UI - propertiesList.add((ComponentInstanceProperty)prop); - input.setProperties(propertiesList); - }else{ - ComponentInstanceInput inputValue = new ComponentInstanceInput(prop); - if(!inputsValueToCreate.contains(inputValue)){ - inputsValueToCreate.add(inputValue);; - } - - inputsToCreate.put(input.getName(), input); - List<ComponentInstanceInput> inputsValueList = input.getInputs(); - if(inputsValueList == null) - inputsValueList = new ArrayList<>(); // adding the property with the new value for UI - inputsValueList.add(inputValue); - input.setInputs(inputsValueList); - } - - return Either.left(input); - - } - - private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ - - while(i >= 1){ - if( i == parsedPropNames.length -1){ - JSONObject jobProp = new JSONObject(); - jobProp.put(GET_INPUT, inputName); - ooj.put(parsedPropNames[i], jobProp); - i--; - return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); - }else{ - JSONObject res = new JSONObject(); - res.put(parsedPropNames[i], ooj); - i --; - res = createJSONValueForProperty (i, parsedPropNames, res, inputName); - return res; - } - } - - return ooj; - } - - public void resetInputName(Map<String, Object> lhm1, String inputName){ - for (Map.Entry<String, Object> entry : lhm1.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { - value = ""; - lhm1.remove(key); - } else if (value instanceof Map) { - Map<String, Object> subMap = (Map<String, Object>)value; - resetInputName(subMap, inputName); - } else { - continue; - } - - } - } - - private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){ - while(index < inputNames.length){ - if(lhm1.containsKey(inputNames[index])){ - Object value = lhm1.get(inputNames[index]); - if (value instanceof Map){ - if(index == inputNames.length -1){ - ((Map) value).put(GET_INPUT, inputName); - return ((Map) value); - - }else{ - index++; - return createInputValue((Map)value, index, inputNames, inputName); - } - }else{ - Map<String, Object> jobProp = new HashMap<>(); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - lhm1.put(inputNames[index], jobProp); - return lhm1; - }else{ - lhm1.put(inputNames[index], jobProp); - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - }else{ - Map<String, Object> jobProp = new HashMap<>(); - lhm1.put(inputNames[index], jobProp); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - return jobProp; - }else{ - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - } - return lhm1; - } + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreComponentInstancesInputs(false); + + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + + if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){ + ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; + log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap()); + return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList())); + } + + /** + * associate properties to a given component instance input + * + * @param instanceId + * @param userId + * @param inputId + * @return + */ + + public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + + if(!instanceId.equals(inputId)){ + + + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny(); + if(ciOp.isPresent()){ + parentId = ciOp.get().getComponentUid(); + } + + } + + filters.setIgnoreInputs(false); + + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId)); + + } + + private Either<String,ResponseFormat> updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) { + String innerType = null; + String propertyType = currentInput.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = currentInput.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes); + + String newValue = currentInput.getDefaultValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + return Either.left(newValue); + } + + private InputDefinition getInputFromInputsListById(List<InputDefinition> componentsOldInputs, InputDefinition input) { + Optional<InputDefinition> foundInput = componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst(); + return foundInput.isPresent() ? foundInput.get() : null; + } + + public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List<InputDefinition> inputs, String userId, boolean shouldLockComp, boolean inTransaction) { + + List<InputDefinition> returnInputs = new ArrayList<>(); + Either<List<InputDefinition>, ResponseFormat> result = null; + org.openecomp.sdc.be.model.Component component = null; + + try { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false); + + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreUsers(false); + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + if (shouldLockComp) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } + + Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + + Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList()); + for (InputDefinition newInput: inputs) { + InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput); + if (currInput == null) { + ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; + log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus.name()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + Either<String, ResponseFormat> updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes); + if ( updateInputObjectValue.isRight()) { + return Either.right(updateInputObjectValue.right().value()); + } + String newValue = updateInputObjectValue.left().value(); + currInput.setDefaultValue(newValue); + currInput.setOwnerId(userId); + Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput); + if(status.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); + return result; + } else { + returnInputs.add(status.left().value()); + } + } + result = Either.left(returnInputs); + return result; + } finally { + if (false == inTransaction) { + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + } + // unlock resource + if (shouldLockComp && component != null) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + } + } + + public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId)); + + } + + public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { + + Either<List<InputDefinition>, ResponseFormat> result = null; + org.openecomp.sdc.be.model.Component component = null; + + try { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); + + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnoreUsers(false); + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + if (shouldLockComp) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } + + Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + + result = propertyDecelerationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi) + .left() + .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)) + .right() + .map(err -> componentsUtils.getResponseFormat(err)); + + return result; + + } finally { + + if (!inTransaction) { + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + } + // unlock resource + if (shouldLockComp && component != null) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + + } + } + + private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List<InputDefinition> inputsToCreate) { + Map<String, InputDefinition> inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName); + assignOwnerIdToInputs(userId, inputsToPersist); + return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId) + .left() + .map(persistedInputs -> inputsToCreate); + } + + private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) { + inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId)); + } + + public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) { + + List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList()); + Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList); + List<InputDefinition> resourceProperties = component.getInputs(); + + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + return Either.right(allDataTypes.right().value()); + } + + Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + + for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) { + String inputName = inputDefinition.getKey(); + inputDefinition.getValue().setName(inputName); + + Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); + if(preparedInputEither.isRight()){ + return Either.right(preparedInputEither.right().value()); + } + + } + if (resourceProperties != null) { + Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); + Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); + if(mergeEither.isRight()){ + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); + } + inputs = mergeEither.left().value(); + } + + Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); + if(assotiateInputsEither.isRight()){ + log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); + } + result = Either.left(assotiateInputsEither.left().value()); + + return result; + } + + /** + * Delete input from service + * + * @param componentId + * @param userId + * + * @param inputId + * @return + */ + public Either<InputDefinition, ResponseFormat> deleteInput(String componentId, String userId, String inputId) { + + Either<InputDefinition, ResponseFormat> deleteEither = null; + if (log.isDebugEnabled()) + log.debug("Going to delete input id: {}", inputId); + + // Validate user (exists) + Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true); + if (userEither.isRight()) { + deleteEither = Either.right(userEither.right().value()); + return deleteEither; + } + + // Get component using componentType, componentId + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnorePolicies(false); + componentParametersView.setIgnoreUsers(false); + + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (componentEither.isRight()) { + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); + return deleteEither; + } + org.openecomp.sdc.be.model.Component component = componentEither.left().value(); + + // Validate inputId is child of the component + Optional<InputDefinition> optionalInput = component.getInputs().stream(). + // filter by ID + filter(input -> input.getUniqueId().equals(inputId)). + // Get the input + findAny(); + if (!optionalInput.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); + } + + InputDefinition inputForDelete = optionalInput.get(); + + // Lock component + Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput"); + if (lockResultEither.isRight()) { + ResponseFormat responseFormat = lockResultEither.right().value(); + deleteEither = Either.right(responseFormat); + return deleteEither; + } + + // Delete input operations + try { + StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); + if (status != StorageOperationStatus.OK) { + log.debug("Component id: {} delete input id: {} failed", componentId, inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + StorageOperationStatus storageOperationStatus = propertyDecelerationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete); + if (storageOperationStatus != StorageOperationStatus.OK) { + log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + deleteEither = Either.left(inputForDelete); + return deleteEither; + } finally { + if (deleteEither == null || deleteEither.isRight()) { + log.debug("Component id: {} delete input id: {} failed", componentId, inputId); + titanDao.rollback(); + } else { + log.debug("Component id: {} delete input id: {} success", componentId, inputId); + titanDao.commit(); + } + unlockComponent(deleteEither, component); + } + } + + private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) { + + + // validate input default values + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + // convert property + ToscaPropertyType type = getType(newInputDefinition.getType()); + if (type != null) { + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + if (newInputDefinition != null) { + SchemaDefinition schema = newInputDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newInputDefinition.getDefaultValue() != null) { + convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); + newInputDefinition.setDefaultValue(convertedValue); + } + } + } + return Either.left(newInputDefinition); + } + + public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { + Either<InputDefinition, ResponseFormat> result = null; + try { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreProperties(false); + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + InputDefinition resObj = op.get(); + + List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId) ; + + resObj.setInputs(inputCIInput); + + + List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ; + + resObj.setProperties(inputProps); + + + result = Either.left(resObj); + + return result; + + } finally { + + if (false == inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java index e7d051290f..cfc2505942 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.InterfaceDefinition; @@ -39,86 +32,86 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; @Component("interfaceLifecycleTypeImportManager") public class InterfaceLifecycleTypeImportManager { - @Resource - private IInterfaceLifecycleOperation interfaceLifecycleOperation; - - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - private static Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class.getName()); - - public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) { - - Either<List<InterfaceDefinition>, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml); - if (interfaces.isRight()) { - ActionStatus status = interfaces.right().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null); - return Either.right(responseFormat); - } - return createInterfacesByDao(interfaces.left().value()); - - } - - private Either<List<InterfaceDefinition>, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) { - return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData)); - - } - - private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) { - List<InterfaceDefinition> createdInterfaces = new ArrayList<>(); - Either<List<InterfaceDefinition>, ResponseFormat> eitherResult = Either.left(createdInterfaces); - Iterator<InterfaceDefinition> interfaceItr = interfacesToCreate.iterator(); - boolean stopDao = false; - while (interfaceItr.hasNext() && !stopDao) { - InterfaceDefinition interfaceDef = interfaceItr.next(); - - log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType()); - - Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef); - if (dataModelResponse.isRight()) { - log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name()); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType()); - eitherResult = Either.right(responseFormat); - stopDao = true; - } - - } else { - createdInterfaces.add(dataModelResponse.left().value()); - } - if (!interfaceItr.hasNext()) { - log.info("lifecycle types were created successfully!!!"); - } - } - return eitherResult; - } - - private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map<String, Object> toscaJson) { - InterfaceDefinition interfaceDef = new InterfaceDefinition(); - interfaceDef.setType(interfaceDefinition); - - Map<String, Operation> operations = new HashMap<String, Operation>(); - - for (Map.Entry<String, Object> entry : toscaJson.entrySet()) { - Operation operation = new Operation(); - Map<String, Object> opProp = (Map<String, Object>) entry.getValue(); - - operation.setDescription((String) opProp.get("description")); - operations.put(entry.getKey(), operation); - } - interfaceDef.setOperationsMap(operations); - return interfaceDef; - } - - public static void setLog(Logger log) { - InterfaceLifecycleTypeImportManager.log = log; - } - + @Resource + private IInterfaceLifecycleOperation interfaceLifecycleOperation; + + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + private static final Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class); + + public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) { + + Either<List<InterfaceDefinition>, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml); + if (interfaces.isRight()) { + ActionStatus status = interfaces.right().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null); + return Either.right(responseFormat); + } + return createInterfacesByDao(interfaces.left().value()); + + } + + private Either<List<InterfaceDefinition>, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) { + return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData)); + + } + + private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) { + List<InterfaceDefinition> createdInterfaces = new ArrayList<>(); + Either<List<InterfaceDefinition>, ResponseFormat> eitherResult = Either.left(createdInterfaces); + Iterator<InterfaceDefinition> interfaceItr = interfacesToCreate.iterator(); + boolean stopDao = false; + while (interfaceItr.hasNext() && !stopDao) { + InterfaceDefinition interfaceDef = interfaceItr.next(); + + log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType()); + + Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef); + if (dataModelResponse.isRight()) { + log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name()); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType()); + eitherResult = Either.right(responseFormat); + stopDao = true; + } + + } else { + createdInterfaces.add(dataModelResponse.left().value()); + } + if (!interfaceItr.hasNext()) { + log.info("lifecycle types were created successfully!!!"); + } + } + return eitherResult; + } + + private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map<String, Object> toscaJson) { + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + interfaceDef.setType(interfaceDefinition); + + Map<String, Operation> operations = new HashMap<String, Operation>(); + + for (Map.Entry<String, Object> entry : toscaJson.entrySet()) { + Operation operation = new Operation(); + Map<String, Object> opProp = (Map<String, Object>) entry.getValue(); + + operation.setDescription((String) opProp.get("description")); + operations.put(entry.getKey(), operation); + } + interfaceDef.setOperationsMap(operations); + return interfaceDef; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java index e9708f50d5..43cf9bdec8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.components.impl; +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.MonitoringDao; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -29,43 +30,41 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("monitoringBusinessLogic") public class MonitoringBusinessLogic { - private static Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class); - @javax.annotation.Resource - private MonitoringDao monitoringDao; + @javax.annotation.Resource + private MonitoringDao monitoringDao; - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - public Either<Boolean, ResponseFormat> logMonitoringEvent(MonitoringEvent monitoringEvent) { - if (monitoringDao == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - ActionStatus status = monitoringDao.addRecord(monitoringEvent); - if (!status.equals(ActionStatus.OK)) { - log.warn("Failed to persist monitoring event: {}", status.name()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(true); - } + public Either<Boolean, ResponseFormat> logMonitoringEvent(MonitoringEvent monitoringEvent) { + if (monitoringDao == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + ActionStatus status = monitoringDao.addRecord(monitoringEvent); + if (!status.equals(ActionStatus.OK)) { + log.warn("Failed to persist monitoring event: {}", status); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(true); + } - public String getEsHost() { + public String getEsHost() { - String res = monitoringDao.getEsHost(); - res = res.replaceAll("[\\[\\]]", ""); - res = res.split(",")[0]; - res = res.replaceAll("[']", ""); - res = res.split(":")[0]; - return res; - } + String res = monitoringDao.getEsHost(); + res = res.replaceAll("[\\[\\]]", ""); + res = res.split(",")[0]; + res = res.replaceAll("[']", ""); + res = res.split(":")[0]; + return res; + } - public String getEsPort() { - return monitoringDao.getEsPort(); - } + public String getEsPort() { + return monitoringDao.getEsPort(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java new file mode 100644 index 0000000000..37a853ccdd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java @@ -0,0 +1,451 @@ +package org.openecomp.sdc.be.components.impl; + +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +/** + * Provides specified business logic to create, retrieve, update, delete a policy + */ +@org.springframework.stereotype.Component("policyBusinessLogic") +public class PolicyBusinessLogic extends BaseBusinessLogic { + + private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. "; + private static final Logger log = LoggerFactory.getLogger(PolicyBusinessLogic.class); + + /** + * Adds the newly created policy of the specified type to the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyTypeName the name of the policy type + * @param userId the user creator id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + + public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { + + Either<PolicyDefinition, ResponseFormat> result = null; + log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId); + Wrapper<Component> component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return createPolicy(policyTypeName, c); + }); + } catch (Exception e) { + log.error("#createPolicy - the exception occurred upon creation of a policy of the type {} for the component {}: ", policyTypeName, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + + unlockComponent(shouldLock, result, component); + } + return result; + } + + /** + * Retrieves the policy of the component by UniqueId + * + * @param componentType + * @param componentId + * @param policyId + * @param userId + * @return + */ + public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + Either<PolicyDefinition, ResponseFormat> result = null; + log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId); + try { + result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(c -> getPolicyById(c, policyId)); + } catch (Exception e) { + log.error("#getPolicy - the exception occurred upon retrieving the policy {} of the component {}: ", policyId, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return result; + } + + /** + * Updates the policy of the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policy + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { + Either<PolicyDefinition, ResponseFormat> result = null; + log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId); + Wrapper<Component> component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return validateAndUpdatePolicy(c, policy); + }); + } catch (Exception e) { + log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + unlockComponent(shouldLock, result, component); + } + return result; + } + + /** + * Deletes the policy from the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + Either<PolicyDefinition, ResponseFormat> result = null; + log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); + Wrapper<Component> component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return deletePolicy(c, policyId); + }); + } catch (Exception e) { + log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e); + } finally { + unlockComponent(shouldLock, result, component); + } + return result; + } + + public Either<PolicyDefinition, ResponseFormat> updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) { + + Either<PolicyDefinition, ResponseFormat> result = null; + log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId); + Component component = null; + + try { + //not right error response + result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true) + .left() + .bind(cmpt -> validateAndUpdatePolicyTargets(cmpt, policyId, targets)); + + return result; + } finally { + + unlockComponentById(result, componentId); + + } + + } + + private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) { + if (!validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)) { + log.debug("Error finding all the targets: {} .", targets); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, StringUtils.join(targets.values()))); + } + return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId); + + } + + private boolean validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) { + Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaFullElement(componentId); + Component parentComponent = componentEither.left().value(); + + return targets.entrySet().stream().noneMatch(t -> checkTargetNotExistOnComponentByType(parentComponent, t)); + } + + private boolean checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) { + + return targetEntry.getValue().stream() + .anyMatch(id -> checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().toString())); + } + + private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) { + if (type.equalsIgnoreCase(PolicyTargetType.GROUPS.getName()) && parentComponent.getGroups() != null) { + return !parentComponent.getGroupById(uniqueId).isPresent(); + } else if (type.equalsIgnoreCase(PolicyTargetType.COMPONENT_INSTANCES.getName()) && parentComponent.getComponentInstances() != null) { + return !parentComponent.getComponentInstanceById(uniqueId).isPresent(); + } + return true; + } + + private PolicyDefinition setPolicyTargets(PolicyDefinition policyDefinition, Map<PolicyTargetType, List<String>> targets) { + policyDefinition.setTargets(targets); + return policyDefinition; + } + + + /** + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param userId the user id + * @return a list of policy properties or an error in a response format + */ + public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId); + try { + return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(cmpt -> getPolicyById(cmpt, policyId)).left().map(PolicyDataDefinition::getProperties); + } finally { + titanDao.commit(); + } + } + + /** + * Updates the policy properties of the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param properties a list of policy properties containing updated values + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a list of policy properties or anerrorin a response format + */ + public Either<List<PropertyDataDefinition>, ResponseFormat> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) { + Either<List<PropertyDataDefinition>, ResponseFormat> result = null; + log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId); + Wrapper<Component> component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left().bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c)); + } catch (Exception e) { + log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (shouldLock && !component.isEmpty()) { + unlockComponent(result, component.getInnerElement()); + } + } + return result; + } + + private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) { + component.setInnerElement(c); + return validateAndUpdatePolicyProperties(c, policyId, properties) + .left() + .map(PolicyDefinition::getProperties); + } + + private void unlockComponent(boolean shouldLock, Either<PolicyDefinition, ResponseFormat> result, Wrapper<Component> component) { + if (shouldLock && !component.isEmpty()) { + unlockComponent(result, component.getInnerElement()); + } + } + + private Either<PolicyDefinition, ResponseFormat> getPolicyById(Component component, String policyId) { + PolicyDefinition policyById = component.getPolicyById(policyId); + if (policyById == null) { + String cmptId = component.getUniqueId(); + log.debug("#getPolicyById - policy with id {} does not exist on component with id {}", policyId, cmptId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId)); + } + return Either.left(policyById); + } + + private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) { + return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component)); + } + + private Either<PolicyDefinition, ResponseFormat> addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { + return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())) + .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { + return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName) + .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) { + if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component))); + } + return Either.left(policyType); + } + + private String getComponentOrResourceTypeName(Component component) { + return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name(); + } + + private Either<Component, ResponseFormat> validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { + Wrapper<Component> component = new Wrapper<>(); + return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(this::validateComponentIsTopologyTemplate) + .left() + .bind(c -> { + component.setInnerElement(c); + return validateCanWorkOnComponent(c, userId); + }) + .left() + .bind(l -> lockComponent(component.getInnerElement(), shouldLock, "policyWritingOperation")) + .either(l -> Either.left(component.getInnerElement()), r -> { + log.error(FAILED_TO_VALIDATE_COMPONENT, componentId); + return Either.right(r); + }); + } + + private Either<Component, ResponseFormat> validateComponentIsTopologyTemplate(Component component) { + if (!component.isTopologyTemplate()) { + log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", component.getToscaType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType())); + } + return Either.left(component); + } + + private Either<Component, ResponseFormat> validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) { + Either<Component, ResponseFormat> result = null; + log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId); + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Policy", false); + if (resp.isRight()) { + log.error("#validateContainerComponentAndUserBeforeReadOperation - failed to validate the user {} before policy processing. ", userId); + result = Either.right(resp.right().value()); + } else { + result = validateComponentExists(componentType, componentId); + if (result.isRight()) { + log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId); + } + return result; + } + return result; + } + + private Either<Component, ResponseFormat> validateComponentExists(ComponentTypeEnum componentType, String componentId) { + + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnorePolicies(false); + filter.setIgnoreUsers(false); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreGroups(false); + return validateComponentExists(componentId, componentType, filter); + } + + + private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicy(Component component, PolicyDefinition policy) { + return getPolicyById(component, policy.getUniqueId()) + .left() + .bind(np -> validateUpdatePolicyBeforeUpdate(policy, np, component.getPolicies())) + .left() + .bind(p -> updatePolicyOfComponent(component, p)); + } + + private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) { + return getPolicyById(component, policyId) + .left() + .bind(p -> validateUpdatePolicyPropertiesBeforeUpdate(p, properties)) + .left().bind(l -> updatePolicyOfComponent(component.getUniqueId(), l)); + } + + private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(String componentId, PolicyDefinition policy) { + return toscaOperationFacade.updatePolicyOfComponent(componentId, policy) + .right() + .bind(r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + if (CollectionUtils.isEmpty(policy.getProperties())) { + log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. "); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); + } + return updatePropertyValues(policy, newProperties); + } + + private Either<PolicyDefinition, ResponseFormat> updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + + Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity())); + for (PropertyDataDefinition newProperty : newProperties) { + if (!oldProperties.containsKey(newProperty.getName())) { + log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. "); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName())); + } + Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(newProperty, true); + if (newPropertyValueEither.isRight()) { + return Either.right(newPropertyValueEither.right().value()); + } + oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither.left().value()); + } + return Either.left(policy); + } + + private Either<PolicyDefinition, ResponseFormat> deletePolicy(Component component, String policyId) { + return getPolicyById(component, policyId) + .left() + .bind(p -> removePolicyFromComponent(component, p)); + } + + private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(Component component, PolicyDefinition policy) { + Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy); + if (updatePolicyRes.isRight()) { + log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value()))); + } else { + log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName()); + return Either.left(updatePolicyRes.left().value()); + } + } + + private Either<PolicyDefinition, ResponseFormat> removePolicyFromComponent(Component component, PolicyDefinition policy) { + StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId()); + if (updatePolicyStatus != StorageOperationStatus.OK) { + log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyStatus))); + } else { + log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus); + return Either.left(policy); + } + } + + private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) { + return validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies) + .right() + .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName()))); + } + + private Either<PolicyDefinition, ResponseFormat> updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) { + if(policy == null){ + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId)); + } + PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets); + return updatePolicyOfComponent(componentId, updatedPolicy); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java new file mode 100644 index 0000000000..fee8ba187c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java @@ -0,0 +1,56 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +@Component +public class PolicyTypeBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(PolicyTypeBusinessLogic.class); + private PolicyTypeOperation policyTypeOperation; + private TitanDao titanDao; + private ComponentsUtils componentsUtils; + private UserValidations userValidations; + + public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, TitanDao titanDao, ComponentsUtils componentsUtils, UserValidations userValidations) { + this.policyTypeOperation = policyTypeOperation; + this.titanDao = titanDao; + this.componentsUtils = componentsUtils; + this.userValidations = userValidations; + } + + public Either<List<PolicyTypeDefinition>, ResponseFormat> getAllPolicyTypes(String userId, String internalComponentType) { + try { + Set<String> excludedPolicyTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping().get(internalComponentType); + return userValidations.validateUserExists(userId, "get policy types", true) + .left() + .bind(user -> getPolicyTypes(excludedPolicyTypes)); + } finally { + titanDao.commit(); + } + } + + private Either<List<PolicyTypeDefinition>, ResponseFormat> getPolicyTypes(Set<String> excludedTypes) { + return policyTypeOperation.getAllPolicyTypes(excludedTypes) + .right() + .bind(this::convertToResponseFormatOrNotFoundErrorToEmptyList); + } + + private Either<List<PolicyTypeDefinition>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus err) { + log.debug("error when trying to fetch policy types: {}", err); + return componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(err); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java index 4a07120994..fed588ff9c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java @@ -20,109 +20,120 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; +import org.openecomp.sdc.be.components.impl.utils.PolicyTypeImportUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; @Component("policyTypeImportManager") public class PolicyTypeImportManager { - @Resource - private IPolicyTypeOperation policyTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Autowired - protected IGroupOperation groupOperation; - @Autowired - private ToscaOperationFacade toscaOperationFacade; - - @Resource - private CommonImportManager commonImportManager; - - public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(String groupTypesYml) { - return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createPolicyTypesFromYml(elementTypeYml), groupTypesList -> createPolicyTypesByDao(groupTypesList), ElementTypeEnum.PolicyType); - } - - private Either<List<PolicyTypeDefinition>, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) { - - return commonImportManager.createElementTypesFromYml(policyTypesYml, (policyTypeName, groupTypeJsonData) -> createPolicyType(policyTypeName, groupTypeJsonData)); - } - - private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) { - return commonImportManager.createElementTypesByDao(policyTypesToCreate, policyType -> validatePolicyType(policyType), policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()), - policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), null); - } - - private Either<ActionStatus, ResponseFormat> validatePolicyType(PolicyTypeDefinition policyType) { - Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK); - if (policyType.getTargets() != null) { - if (policyType.getTargets().isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType()); - result = Either.right(responseFormat); - } - if (result.isLeft()) { - for (String targetName : policyType.getTargets()) { - - boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetName).isLeft();; - if (!isValid) { - isValid = groupOperation.isGroupExist(targetName, false); - } - if (!isValid) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetName); - result = Either.right(responseFormat); - break; - } - } - } - } - - return result; - } - - private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) { - - PolicyTypeDefinition policyType = new PolicyTypeDefinition(); - - if (toscaJson != null) { - // Description - final Consumer<String> descriptionSetter = description -> policyType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer<String> derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values)); - // Metadata - final Consumer<Map<String, String>> metadataSetter = metadata -> policyType.setMetadata(metadata); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); - // Targets - final Consumer<List<String>> targetsSetter = targets -> policyType.setTargets(targets); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter); - - policyType.setType(groupTypeName); - - policyType.setHighestVersion(true); - - policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); - } - return policyType; - } + @Resource + private IPolicyTypeOperation policyTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Autowired + protected IGroupOperation groupOperation; + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Resource + private CommonImportManager commonImportManager; + + public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(String policyTypesYml) { + return commonImportManager.createElementTypes(policyTypesYml, this::createPolicyTypesFromYml, this::upsertPolicyTypesByDao, ElementTypeEnum.PolicyType); + } + + private Either<List<PolicyTypeDefinition>, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) { + + return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType); + } + + private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) { + return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()), + policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), this::updatePolicyType); + } + + private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) { + if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) { + return policyTypeAlreadyExists(); + } + return policyTypeOperation.updatePolicyType(newPolicyType, oldPolicyType); + } + + private Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeAlreadyExists() { + return Either.right(StorageOperationStatus.OK); + } + + private Either<ActionStatus, ResponseFormat> validatePolicyType(PolicyTypeDefinition policyType) { + Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK); + if (policyType.getTargets() != null) { + if (policyType.getTargets().isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType()); + result = Either.right(responseFormat); + } + if (result.isLeft()) { + for (String targetId : policyType.getTargets()) { + boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft(); + if (!isValid) { + isValid = groupOperation.isGroupExist(targetId, false); + } + if (!isValid) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId); + result = Either.right(responseFormat); + break; + } + } + } + } + + + return result; + } + + private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) { + + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + + if (toscaJson != null) { + // Description + final Consumer<String> descriptionSetter = description -> policyType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer<String> derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values)); + // Metadata + final Consumer<Map<String, String>> metadataSetter = metadata -> policyType.setMetadata(metadata); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); + // Targets + final Consumer <List<String>> targetsSetter = targets -> policyType.setTargets(targets); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter); + + policyType.setType(groupTypeName); + + policyType.setHighestVersion(true); + + policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); + } + return policyType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java index da64f3f5b7..ab6ff24676 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -48,846 +41,848 @@ import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("productBusinessLogic") public class ProductBusinessLogic extends ComponentBusinessLogic { - private static final String PRODUCT_FULL_NAME = "full"; - private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated"; - private static Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class.getName()); - private static final String INITIAL_VERSION = "0.1"; - private static List<Role> creationRoles; - private static List<Role> updateRoles; - private static List<Role> contactsRoles; - - public ProductBusinessLogic() { - creationRoles = new ArrayList<>(); - updateRoles = new ArrayList<>(); - contactsRoles = new ArrayList<>(); - - // only PM is allowed to create/update products - creationRoles.add(Role.PRODUCT_MANAGER); - updateRoles.add(Role.PRODUCT_MANAGER); - // Only PM is allowed to be product contacts - contactsRoles.add(Role.PRODUCT_MANAGER); - } - - @Autowired - private IElementOperation elementDao; - - @Autowired - private ProductComponentInstanceBusinessLogic productComponentInstanceBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - public Either<Product, ResponseFormat> createProduct(Product product, User user) { - AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE; - ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; - - // validate user - should be first to get the maximum auditing info in - // case of subsequent failures - log.debug("get user from DB"); - Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Product", product, actionEnum, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, product, creationRoles, actionEnum, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - if (product == null) { - log.debug("Invalid product json. Check product servlet log for createProduct entry params"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - return Either.right(responseFormat); - } - - // warn about non-updatable fields - checkUnupdatableProductFields(product); - - Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum); - if (validateProductResponse.isRight()) { - return Either.right(validateProductResponse.right().value()); - } - - log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, "Create Product"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult); - - try { - Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product); - - if (createProductEither.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - return Either.right(responseFormat); - } - - log.debug("Product created successfully"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - - // //Add product to cache - Product createdProduct = createProductEither.left().value(); - // cacheManagerOperation.updateComponentInCache(createdProduct.getUniqueId(), - // createdProduct.getLastUpdateDate(), NodeTypeEnum.Product); - - return Either.left(createdProduct); - - } finally { - graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product); - } - - } - - private void checkUnupdatableProductFields(Product product) { - checkComponentFieldsForOverrideAttempt(product); - if (product.getNormalizedName() != null) { - log.info("NormalizedName cannot be defined by user. This field will be overridden by the application"); - } - } - - private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) { - - Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum); - if (validateProductFields.isRight()) { - return Either.right(validateProductFields.right().value()); - } - - if (product.getIsActive() == null) { - log.debug("no isActive value was provided, setting to default: false"); - product.setIsActive(false); - } - - product.setCreatorUserId(user.getUserId()); - - // enrich object - log.debug("enrich product with version and state"); - product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - product.setVersion(INITIAL_VERSION); - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - product.setInvariantUUID(invariantUUID); - - return Either.left(product); - } - - private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) { - - // To be removed in 1607 - // See below - String oldName = product.getName(); - - Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum); - if (componentNameValidation.isRight()) { - return componentNameValidation; - } - - Either<Boolean, ResponseFormat> componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum); - if (componentNameUniquenessValidation.isRight()) { - return componentNameUniquenessValidation; - } - - // To be removed in 1607 and replaced with generic - // validateTagsListAndRemoveDuplicates() - // See comments on the validateTagsListAndRemoveDuplicates(user, - // product, oldName, actionEnum) function - Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum); - if (tagsValidation.isRight()) { - return tagsValidation; - } - - Either<Boolean, ResponseFormat> validateIconResponse = validateIcon(user, product, actionEnum); - if (validateIconResponse.isRight()) { - return validateIconResponse; - } - - Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; - } - Either<Boolean, ResponseFormat> categoryValidation = validateGrouping(user, product, actionEnum); - if (categoryValidation.isRight()) { - return categoryValidation; - } - - Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum); - if (contactsListValidation.isRight()) { - return contactsListValidation; - } - - Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum); - if (productFullNameValidation.isRight()) { - return productFullNameValidation; - } - - Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, product, actionEnum); - if (descValidation.isRight()) { - return descValidation; - } - - return Either.left(true); - } - - public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Product Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map<String, Boolean> result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) { - List<String> contacts = product.getContacts(); - if (!ValidationUtils.validateListNotEmpty(contacts)) { - log.debug("Contacts list cannot be empty for product {}", product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - boolean isProductCreatorInContacts = false; - String modifierUserId = user.getUserId(); - for (String contact : contacts) { - if (contact.equals(modifierUserId)) { - log.trace("modifier userId found in product contacts"); - isProductCreatorInContacts = true; - // No need to validate for this userId - it's modifier's - continue; - } - if (!ValidationUtils.validateContactId(contact)) { - log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - User contactUser = new User(); - contactUser.setUserId(contact); - Either<User, ResponseFormat> validateUser = validateUserExists(contact, "Create Product", false); - if (validateUser.isRight()) { - log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - contactUser = validateUser.left().value(); - - Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(contactUser, contactsRoles); - if (validateUserRole.isRight()) { - log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - } - - if (!isProductCreatorInContacts) { - log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId); - contacts.add(modifierUserId); - } - - // passed - setting all contacts userIds to lowercase - List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList()); - ValidationUtils.removeDuplicateFromList(tempContacts); - product.setContacts(tempContacts); - - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateGrouping(User user, Product product, AuditingActionEnum actionEnum) { - List<CategoryDefinition> categories = product.getCategories(); - if (categories == null || categories.isEmpty()) { - log.debug("Grouping list is empty for product: {}", product.getName()); - return Either.left(true); - } - Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>(); - // remove duplicated entries - for (CategoryDefinition cat : categories) { - String catName = cat.getName(); - if (ValidationUtils.validateStringNotEmpty(catName) == false) { - // error missing cat name - log.debug("Missing category name for product: {}", product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - Map<String, Set<String>> catEntry = nonDuplicatedCategories.get(catName); - if (catEntry == null) { - catEntry = new HashMap<String, Set<String>>(); - nonDuplicatedCategories.put(catName, catEntry); - } - List<SubCategoryDefinition> subcategories = cat.getSubcategories(); - if (subcategories == null || subcategories.isEmpty()) { - // error missing subcat for cat - log.debug("Missing sub-categories for category {} in product {}", catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - for (SubCategoryDefinition subcat : subcategories) { - String subCatName = subcat.getName(); - if (ValidationUtils.validateStringNotEmpty(subCatName) == false) { - // error missing sub cat name for cat - log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - Set<String> subcatEntry = catEntry.get(subCatName); - if (subcatEntry == null) { - subcatEntry = new HashSet<String>(); - catEntry.put(subCatName, subcatEntry); - } - List<GroupingDefinition> groupings = subcat.getGroupings(); - for (GroupingDefinition group : groupings) { - String groupName = group.getName(); - if (ValidationUtils.validateStringNotEmpty(groupName) == false) { - // error missing grouping for sub cat name and cat - log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - if (!subcatEntry.contains(groupName)) { - subcatEntry.add(groupName); - } else { - log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName); - } - } - } - } // for end of checking duplicated - // validate existence - Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories(); - - if (allProductCategories.isRight()) { - log.debug("No product categories {}", allProductCategories.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - boolean catExist; - // convert non-duplicated to data modeling format and update in the - // input object - List<CategoryDefinition> newCatList = new ArrayList<CategoryDefinition>(); - - // over all categories from request - for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) { - catExist = false; - CategoryDefinition categoryDefinition = null; - // over all categories from Titan - List<CategoryDefinition> categoriesList = allProductCategories.left().value(); - if (categoriesList != null) { - for (CategoryDefinition catInDb : categoriesList) { - if (entry.getKey().equals(catInDb.getName())) { - catExist = true; - boolean subcatExist; - // copy data - categoryDefinition = new CategoryDefinition(catInDb); - SubCategoryDefinition subCategory = null; - - Map<String, Set<String>> subcats = entry.getValue(); - for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) { - subcatExist = false; - List<SubCategoryDefinition> subcategoriesList = catInDb.getSubcategories(); - if (subcategoriesList != null) { - for (SubCategoryDefinition subcatInDb : subcategoriesList) { - if (subcatInDb.getName().equals(subcat.getKey())) { - // copy data - subCategory = new SubCategoryDefinition(subcatInDb); - subcatExist = true; - Set<String> grouping = subcat.getValue(); - boolean groupExist; - GroupingDefinition groupingDefinition = null; - for (String group : grouping) { - groupExist = false; - List<GroupingDefinition> groupings = subcatInDb.getGroupings(); - if (groupings != null) { - for (GroupingDefinition groupInDb : groupings) { - if (groupInDb.getName().equals(group)) { - groupExist = true; - groupingDefinition = new GroupingDefinition(groupInDb); - } - } - } - if (!groupExist) { - // error grouping isn't defined - // in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - subCategory.addGrouping(groupingDefinition); - } - } - } - } - if (!subcatExist) { - // error sub category isn't defined in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - categoryDefinition.addSubCategory(subCategory); - } - } - } - } - if (!catExist) { - // error category isn't defined in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - newCatList.add(categoryDefinition); - } - product.setCategories(newCatList); - return Either.left(true); - } - - public Either<Product, ResponseFormat> getProduct(String productId, User user) { - String ecompErrorContext = "Get product"; - Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); - - if (storageStatus.isRight()) { - log.debug("failed to get resource by id {}", productId); - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - // TODO check error - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue())); - } else { - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - } - return Either.left(storageStatus.left().value()); - } - - public Either<Product, ResponseFormat> deleteProduct(String productId, User user) { - String ecompErrorContext = "Delete product"; - Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId); - - if (storageStatus.isRight()) { - log.debug("failed to delete resource by id {}", productId); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - return Either.left(storageStatus.left().value()); - } - - private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { - String fullName = product.getFullName(); - if (!ValidationUtils.validateStringNotEmpty(fullName)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(errorResponse, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(errorResponse); - } - - fullName = ValidationUtils.removeNoneUtf8Chars(fullName); - fullName = ValidationUtils.removeHtmlTags(fullName); - fullName = ValidationUtils.normaliseWhitespace(fullName); - fullName = ValidationUtils.stripOctets(fullName); - - if (!ValidationUtils.validateProductFullNameLength(fullName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - if (!ValidationUtils.validateIsEnglish(fullName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - product.setFullName(fullName); - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { - String name = product.getName(); - if (!ValidationUtils.validateStringNotEmpty(name)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - // Product name is required to have same validation and normalization as - // category - if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name); - - if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - product.setName(normalizedName4Display); - String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display); - product.setNormalizedName(normalizedName4Uniqueness); - - return Either.left(true); - } - - // This is a workaround for a current tag--->product name behaviour, which - // will be changed in 1607. - // It was agreed with Ella on 23/2/16 that the tag validation of product - // will be made against the old product name (before normalization), - // and in 1607 US will be defined where UI will no longer pass tag of - // component name, and BE will add it by itself after all needed - // normalizations. - private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) { - List<String> tagsList = product.getTags(); - - Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT); - if (validateTags.isRight()) { - ResponseFormat responseFormat = validateTags.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - ValidationUtils.removeDuplicateFromList(tagsList); - return Either.left(true); - } - - @Override - public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) { - - } - - public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) { - ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; - Either<User, ResponseFormat> eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - if (updatedProduct == null) { - log.debug("Invalid product json. Check product servlet log for updateProduct entry params"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - - Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); - if (storageStatus.isRight()) { - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); - } - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); - } - - Product currentProduct = storageStatus.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) { - log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct); - if (validationRsponse.isRight()) { - log.info("product update metadata: validations field."); - return validationRsponse; - } - - Product productToUpdate = validationRsponse.left().value(); - // lock resource - Either<Boolean, ResponseFormat> lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); - if (updateResponse.isRight()) { - toscaOperationFacade.rollback(); - log.debug("failed to update product {}", productToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - toscaOperationFacade.commit(); - return Either.left(updateResponse.left().value()); - } finally { - graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product); - } - } - - private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion()); - Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateFullName(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateCategory(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateContactList(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateTags(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - if (updatedProduct.getIsActive() != null) { - currentProduct.setIsActive(updatedProduct.getIsActive()); - } - - response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String currentInvariantUuid = currentProduct.getInvariantUUID(); - String updatedInvariantUuid = updatedProduct.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Product invariant UUID is automatically set and cannot be updated"); - updatedProduct.setInvariantUUID(currentInvariantUuid); - } - return Either.left(currentProduct); - - } - - private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) { - String updatedProductName = updatedProduct.getName(); - String tags = ""; - String currentProductName = currentProduct.getName(); - if (updatedProductName != null) { - Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null); - if (validatProductNameResponse.isRight()) { - ResponseFormat errorRespons = validatProductNameResponse.right().value(); - return Either.right(errorRespons); - } - updatedProductName = updatedProduct.getName(); - if (!currentProductName.equals(updatedProductName)) { - Either<Boolean, ResponseFormat> productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null); - if (productNameUniquenessValidation.isRight()) { - return productNameUniquenessValidation; - } - currentProduct.setName(updatedProductName); - tags = updatedProductName; - updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName); - currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName)); - List<String> updatedTags = updatedProduct.getTags(); - // As discussed with Ella currently (1604) we are not removing - // the old name from tags. - if (updatedTags == null) { - updatedTags = currentProduct.getTags(); - } - updatedTags.add(tags); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) { - String updatedProductName = updatedProduct.getFullName(); - String currentProductName = currentProduct.getFullName(); - if (updatedProductName != null && !currentProductName.equals(updatedProductName)) { - Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null); - if (validatProductNameResponse.isRight()) { - ResponseFormat errorRespons = validatProductNameResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setFullName(updatedProduct.getFullName()); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { - List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories(); - - Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null); - if (validatCategoryResponse.isRight()) { - ResponseFormat errorResponse = validatCategoryResponse.right().value(); - return Either.right(errorResponse); - } - - categoryUpdated = updatedProduct.getCategories(); - if (categoryUpdated != null) { - currentProduct.setCategories(categoryUpdated); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) { - List<String> updatedContacts = updatedProduct.getContacts(); - List<String> currentContacts = currentProduct.getContacts(); - if (updatedContacts != null) { - if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) { - Either<Boolean, ResponseFormat> validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setContacts(updatedProduct.getContacts()); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) { - List<String> tagsUpdated = updatedProduct.getTags(); - List<String> tagsCurrent = currentProduct.getTags(); - if (tagsUpdated != null) { - if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setTags(updatedProduct.getTags()); - } - } - return Either.left(true); - } - - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - // markAsDeleted isnt implemented yet - return Either.left(new ArrayList<>()); - } - - @Override - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateCategoryDisplayNameFormat(tag); - } - - public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); - if (storageStatus.isRight()) { - log.debug("failed to get service by name {} and version {}", productName, productVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName)); - } - Product product = storageStatus.left().value(); - return Either.left(product); - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return productComponentInstanceBusinessLogic; - } - - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - @Override - public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, - List<String> dataParamsToReturn) { - // TODO Auto-generated method stub - return null; - } + private static final String PRODUCT_FULL_NAME = "full"; + private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated"; + private static final Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class); + private static final String INITIAL_VERSION = "0.1"; + private static List<Role> creationRoles; + private static List<Role> updateRoles; + private static List<Role> contactsRoles; + + public ProductBusinessLogic() { + creationRoles = new ArrayList<>(); + updateRoles = new ArrayList<>(); + contactsRoles = new ArrayList<>(); + + // only PM is allowed to create/update products + creationRoles.add(Role.PRODUCT_MANAGER); + updateRoles.add(Role.PRODUCT_MANAGER); + // Only PM is allowed to be product contacts + contactsRoles.add(Role.PRODUCT_MANAGER); + } + + @Autowired + private IElementOperation elementDao; + + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + public Either<Product, ResponseFormat> createProduct(Product product, User user) { + AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE; + ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; + + // validate user - should be first to get the maximum auditing info in + // case of subsequent failures + log.debug("get user from DB"); + Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Product", product, actionEnum, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, product, creationRoles, actionEnum, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + if (product == null) { + log.debug("Invalid product json. Check product servlet log for createProduct entry params"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + return Either.right(responseFormat); + } + + // warn about non-updatable fields + checkUnupdatableProductFields(product); + + Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum); + if (validateProductResponse.isRight()) { + return Either.right(validateProductResponse.right().value()); + } + + log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, "Create Product"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult); + + try { + Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product); + + if (createProductEither.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + return Either.right(responseFormat); + } + + log.debug("Product created successfully"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + + Product createdProduct = createProductEither.left().value(); + + return Either.left(createdProduct); + + } finally { + graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product); + } + + } + + private void checkUnupdatableProductFields(Product product) { + checkComponentFieldsForOverrideAttempt(product); + if (product.getNormalizedName() != null) { + log.info("NormalizedName cannot be defined by user. This field will be overridden by the application"); + } + } + + private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) { + + Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum); + if (validateProductFields.isRight()) { + return Either.right(validateProductFields.right().value()); + } + + if (product.getIsActive() == null) { + log.debug("no isActive value was provided, setting to default: false"); + product.setIsActive(false); + } + + product.setCreatorUserId(user.getUserId()); + + // enrich object + log.debug("enrich product with version and state"); + product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + product.setVersion(INITIAL_VERSION); + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + product.setInvariantUUID(invariantUUID); + + return Either.left(product); + } + + private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) { + + // To be removed in 1607 + // See below + String oldName = product.getName(); + + Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum); + if (componentNameValidation.isRight()) { + return componentNameValidation; + } + + Either<Boolean, ResponseFormat> componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum); + if (componentNameUniquenessValidation.isRight()) { + return componentNameUniquenessValidation; + } + + // To be removed in 1607 and replaced with generic + // validateTagsListAndRemoveDuplicates() + // See comments on the validateTagsListAndRemoveDuplicates(user, + // product, oldName, actionEnum) function + Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum); + if (tagsValidation.isRight()) { + return tagsValidation; + } + + Either<Boolean, ResponseFormat> validateIconResponse = validateIcon(user, product, actionEnum); + if (validateIconResponse.isRight()) { + return validateIconResponse; + } + + Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum); + if (projectCodeValidation.isRight()) { + return projectCodeValidation; + } + Either<Boolean, ResponseFormat> categoryValidation = validateGrouping(user, product, actionEnum); + if (categoryValidation.isRight()) { + return categoryValidation; + } + + Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum); + if (contactsListValidation.isRight()) { + return contactsListValidation; + } + + Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum); + if (productFullNameValidation.isRight()) { + return productFullNameValidation; + } + + Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, product, actionEnum); + if (descValidation.isRight()) { + return descValidation; + } + + return Either.left(true); + } + + public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Product Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map<String, Boolean> result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) { + List<String> contacts = product.getContacts(); + if (!ValidationUtils.validateListNotEmpty(contacts)) { + log.debug("Contacts list cannot be empty for product {}", product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + boolean isProductCreatorInContacts = false; + String modifierUserId = user.getUserId(); + for (String contact : contacts) { + if (contact.equals(modifierUserId)) { + log.trace("modifier userId found in product contacts"); + isProductCreatorInContacts = true; + // No need to validate for this userId - it's modifier's + continue; + } + if (!ValidationUtils.validateContactId(contact)) { + log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + User contactUser = new User(); + contactUser.setUserId(contact); + Either<User, ResponseFormat> validateUser = validateUserExists(contact, "Create Product", false); + if (validateUser.isRight()) { + log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + contactUser = validateUser.left().value(); + + Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(contactUser, contactsRoles); + if (validateUserRole.isRight()) { + log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + } + + if (!isProductCreatorInContacts) { + log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId); + contacts.add(modifierUserId); + } + + // passed - setting all contacts userIds to lowercase + List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList()); + ValidationUtils.removeDuplicateFromList(tempContacts); + product.setContacts(tempContacts); + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateGrouping(User user, Product product, AuditingActionEnum actionEnum) { + List<CategoryDefinition> categories = product.getCategories(); + if (categories == null || categories.isEmpty()) { + log.debug("Grouping list is empty for product: {}", product.getName()); + return Either.left(true); + } + Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>(); + // remove duplicated entries + for (CategoryDefinition cat : categories) { + String catName = cat.getName(); + if (ValidationUtils.validateStringNotEmpty(catName) == false) { + // error missing cat name + log.debug("Missing category name for product: {}", product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + Map<String, Set<String>> catEntry = nonDuplicatedCategories.get(catName); + if (catEntry == null) { + catEntry = new HashMap<String, Set<String>>(); + nonDuplicatedCategories.put(catName, catEntry); + } + List<SubCategoryDefinition> subcategories = cat.getSubcategories(); + if (subcategories == null || subcategories.isEmpty()) { + // error missing subcat for cat + log.debug("Missing sub-categories for category {} in product {}", catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + for (SubCategoryDefinition subcat : subcategories) { + String subCatName = subcat.getName(); + if (ValidationUtils.validateStringNotEmpty(subCatName) == false) { + // error missing sub cat name for cat + log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + Set<String> subcatEntry = catEntry.get(subCatName); + if (subcatEntry == null) { + subcatEntry = new HashSet<String>(); + catEntry.put(subCatName, subcatEntry); + } + List<GroupingDefinition> groupings = subcat.getGroupings(); + for (GroupingDefinition group : groupings) { + String groupName = group.getName(); + if (ValidationUtils.validateStringNotEmpty(groupName) == false) { + // error missing grouping for sub cat name and cat + log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + if (!subcatEntry.contains(groupName)) { + subcatEntry.add(groupName); + } else { + log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName); + } + } + } + } // for end of checking duplicated + // validate existence + Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories(); + + if (allProductCategories.isRight()) { + log.debug("No product categories {}", allProductCategories.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + boolean catExist; + // convert non-duplicated to data modeling format and update in the + // input object + List<CategoryDefinition> newCatList = new ArrayList<CategoryDefinition>(); + + // over all categories from request + for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) { + catExist = false; + CategoryDefinition categoryDefinition = null; + // over all categories from Titan + List<CategoryDefinition> categoriesList = allProductCategories.left().value(); + if (categoriesList != null) { + for (CategoryDefinition catInDb : categoriesList) { + if (entry.getKey().equals(catInDb.getName())) { + catExist = true; + boolean subcatExist; + // copy data + categoryDefinition = new CategoryDefinition(catInDb); + SubCategoryDefinition subCategory = null; + + Map<String, Set<String>> subcats = entry.getValue(); + for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) { + subcatExist = false; + List<SubCategoryDefinition> subcategoriesList = catInDb.getSubcategories(); + if (subcategoriesList != null) { + for (SubCategoryDefinition subcatInDb : subcategoriesList) { + if (subcatInDb.getName().equals(subcat.getKey())) { + // copy data + subCategory = new SubCategoryDefinition(subcatInDb); + subcatExist = true; + Set<String> grouping = subcat.getValue(); + boolean groupExist; + GroupingDefinition groupingDefinition = null; + for (String group : grouping) { + groupExist = false; + List<GroupingDefinition> groupings = subcatInDb.getGroupings(); + if (groupings != null) { + for (GroupingDefinition groupInDb : groupings) { + if (groupInDb.getName().equals(group)) { + groupExist = true; + groupingDefinition = new GroupingDefinition(groupInDb); + } + } + } + if (!groupExist) { + // error grouping isn't defined + // in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + subCategory.addGrouping(groupingDefinition); + } + } + } + } + if (!subcatExist) { + // error sub category isn't defined in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + categoryDefinition.addSubCategory(subCategory); + } + } + } + } + if (!catExist) { + // error category isn't defined in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + newCatList.add(categoryDefinition); + } + product.setCategories(newCatList); + return Either.left(true); + } + + public Either<Product, ResponseFormat> getProduct(String productId, User user) { + String ecompErrorContext = "Get product"; + Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); + + if (storageStatus.isRight()) { + log.debug("failed to get resource by id {}", productId); + if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + // TODO check error + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue())); + } else { + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + } + return Either.left(storageStatus.left().value()); + } + + public Either<Product, ResponseFormat> deleteProduct(String productId, User user) { + String ecompErrorContext = "Delete product"; + Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId); + + if (storageStatus.isRight()) { + log.debug("failed to delete resource by id {}", productId); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + return Either.left(storageStatus.left().value()); + } + + private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { + String fullName = product.getFullName(); + if (!ValidationUtils.validateStringNotEmpty(fullName)) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(errorResponse, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(errorResponse); + } + + fullName = ValidationUtils.removeNoneUtf8Chars(fullName); + fullName = ValidationUtils.removeHtmlTags(fullName); + fullName = ValidationUtils.normaliseWhitespace(fullName); + fullName = ValidationUtils.stripOctets(fullName); + + if (!ValidationUtils.validateProductFullNameLength(fullName)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + if (!ValidationUtils.validateIsEnglish(fullName)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + product.setFullName(fullName); + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { + String name = product.getName(); + if (!ValidationUtils.validateStringNotEmpty(name)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + // Product name is required to have same validation and normalization as + // category + if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name); + + if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + product.setName(normalizedName4Display); + String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display); + product.setNormalizedName(normalizedName4Uniqueness); + + return Either.left(true); + } + + // This is a workaround for a current tag--->product name behaviour, which + // will be changed in 1607. + // It was agreed with Ella on 23/2/16 that the tag validation of product + // will be made against the old product name (before normalization), + // and in 1607 US will be defined where UI will no longer pass tag of + // component name, and BE will add it by itself after all needed + // normalizations. + private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) { + List<String> tagsList = product.getTags(); + + Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT); + if (validateTags.isRight()) { + ResponseFormat responseFormat = validateTags.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + ValidationUtils.removeDuplicateFromList(tagsList); + return Either.left(true); + } + + @Override + public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) { + + } + + public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) { + ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; + Either<User, ResponseFormat> eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + if (updatedProduct == null) { + log.debug("Invalid product json. Check product servlet log for updateProduct entry params"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + + Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId); + if (storageStatus.isRight()) { + if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); + } + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); + } + + Product currentProduct = storageStatus.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) { + log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct); + if (validationRsponse.isRight()) { + log.info("product update metadata: validations field."); + return validationRsponse; + } + + Product productToUpdate = validationRsponse.left().value(); + // lock resource + Either<Boolean, ResponseFormat> lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); + if (updateResponse.isRight()) { + toscaOperationFacade.rollback(); + log.debug("failed to update product {}", productToUpdate.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + toscaOperationFacade.commit(); + return Either.left(updateResponse.left().value()); + } finally { + graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product); + } + } + + private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion()); + Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateFullName(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateCategory(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateContactList(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateTags(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + if (updatedProduct.getIsActive() != null) { + currentProduct.setIsActive(updatedProduct.getIsActive()); + } + + response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String currentInvariantUuid = currentProduct.getInvariantUUID(); + String updatedInvariantUuid = updatedProduct.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Product invariant UUID is automatically set and cannot be updated"); + updatedProduct.setInvariantUUID(currentInvariantUuid); + } + return Either.left(currentProduct); + + } + + private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) { + String updatedProductName = updatedProduct.getName(); + String tags = ""; + String currentProductName = currentProduct.getName(); + if (updatedProductName != null) { + Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null); + if (validatProductNameResponse.isRight()) { + ResponseFormat errorRespons = validatProductNameResponse.right().value(); + return Either.right(errorRespons); + } + updatedProductName = updatedProduct.getName(); + if (!currentProductName.equals(updatedProductName)) { + Either<Boolean, ResponseFormat> productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null); + if (productNameUniquenessValidation.isRight()) { + return productNameUniquenessValidation; + } + currentProduct.setName(updatedProductName); + tags = updatedProductName; + updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName); + currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName)); + List<String> updatedTags = updatedProduct.getTags(); + // As discussed with Ella currently (1604) we are not removing + // the old name from tags. + if (updatedTags == null) { + updatedTags = currentProduct.getTags(); + } + updatedTags.add(tags); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) { + String updatedProductName = updatedProduct.getFullName(); + String currentProductName = currentProduct.getFullName(); + if (updatedProductName != null && !currentProductName.equals(updatedProductName)) { + Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null); + if (validatProductNameResponse.isRight()) { + ResponseFormat errorRespons = validatProductNameResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setFullName(updatedProduct.getFullName()); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { + List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories(); + + Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null); + if (validatCategoryResponse.isRight()) { + ResponseFormat errorResponse = validatCategoryResponse.right().value(); + return Either.right(errorResponse); + } + + categoryUpdated = updatedProduct.getCategories(); + if (categoryUpdated != null) { + currentProduct.setCategories(categoryUpdated); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) { + List<String> updatedContacts = updatedProduct.getContacts(); + List<String> currentContacts = currentProduct.getContacts(); + if (updatedContacts != null) { + if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) { + Either<Boolean, ResponseFormat> validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setContacts(updatedProduct.getContacts()); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) { + List<String> tagsUpdated = updatedProduct.getTags(); + List<String> tagsCurrent = currentProduct.getTags(); + if (tagsUpdated != null) { + if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { + Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setTags(updatedProduct.getTags()); + } + } + return Either.left(true); + } + + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + // markAsDeleted isnt implemented yet + return Either.left(new ArrayList<>()); + } + + @Override + protected boolean validateTagPattern(String tag) { + return ValidationUtils.validateCategoryDisplayNameFormat(tag); + } + + public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); + if (storageStatus.isRight()) { + log.debug("failed to get service by name {} and version {}", productName, productVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName)); + } + Product product = storageStatus.left().value(); + return Either.left(product); + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + @Override + public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, + List<String> dataParamsToReturn) { + // TODO Auto-generated method stub + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java deleted file mode 100644 index 73f72216d2..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.springframework.stereotype.Component; - -@Component("productComponentInstanceBusinessLogic") -public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - // TODO Pavel this might be also a resource? - return NodeTypeEnum.Service; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - // TODO Auto-generated method stub - return ComponentTypeEnum.SERVICE_INSTANCE; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index ff26ced5c9..9cc4b9cd3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -20,16 +20,8 @@ package org.openecomp.sdc.be.components.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Supplier; - -import javax.servlet.ServletContext; - +import com.google.gson.JsonElement; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -41,20 +33,17 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.resources.data.EntryData; -import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -62,513 +51,479 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Supplier; @Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_PROPERTY = "CreateProperty"; - - private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName()); - - private static final String EMPTY_VALUE = null; - - private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() { - Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - return eitherAllDataTypes; - } - - /** - * Create new property on resource in graph - * - * @param resourceId - * @param propertyName - * @param newPropertyDefinition - * @param userId - * @return Either<PropertyDefinition, ActionStatus> - */ - public Either<EntryData<String, PropertyDefinition>, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { - - Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Property", false); - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - // Get the resource from DB - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return result; - } - Resource resource = status.left().value(); - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return result; - } - - // verify property not exist in resource - List<PropertyDefinition> resourceProperties = resource.getProperties(); - - if (resourceProperties != null) { - if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); - return result; - } - } - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - - // validate property default values - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - // convert property - ToscaPropertyType type = getType(newPropertyDefinition.getType()); - if (type != null) { - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - if (newPropertyDefinition != null) { - SchemaDefinition schema = newPropertyDefinition.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (prop != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newPropertyDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); - newPropertyDefinition.setDefaultValue(convertedValue); - } - } - } - - // add the new property to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus - // from componentsUtils - Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - PropertyDefinition createdPropertyDefinition = either.left().value(); - EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition); - result = Either.left(property); - return result; - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - /** - * Get property of resource - * - * @param resourceId - * @param propertyId - * @param userId - * @return - */ - public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // Get the resource from DB - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - // verify property exist in resource - List<PropertyDefinition> properties = resource.getProperties(); - if (properties == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); - } - for (PropertyDefinition property : properties) { - if (property.getUniqueId().equals(propertyId) ) { - Map<String, PropertyDefinition> propMap = new HashMap<>(); - propMap.put(property.getName(), property); - return Either.left(propMap.entrySet().iterator().next()); - } - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); - } - - private boolean isPropertyBelongsToResource(PropertyDataDefinition property, String resourceId) { - return property.getOwnerId() == null || property.getOwnerId().equals(resourceId); - } - - /** - * delete property of resource from graph - * - * @param resourceId - * @param propertyId - * @param userId - * @return - */ - public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { - - Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null; - - Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - - // Get the resource from DB - Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId); - if (getResourceRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return result; - } - Resource resource = getResourceRes.left().value(); - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return result; - } - - // verify property exist in resource - Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); - if (statusGetProperty.isRight()) { - result = Either.right(statusGetProperty.right().value()); - return result; - } - - StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); - if (status != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); - return result; - } - // propertyOperation.getTitanGenericDao().commit(); - result = Either.left(statusGetProperty.left().value()); - return result; - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - } - - /** - * update property - * - * @param resourceId - * @param propertyId - * @param newPropertyDefinition - * @param userId - * @return - */ - public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) { - - Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null; - - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); - if (statusGetProperty.isRight()) { - result = Either.right(statusGetProperty.right().value()); - return result; - } - String propertyName = statusGetProperty.left().value().getKey(); - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - - Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - - Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes); - if (either.isRight()) { - log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - - either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value()); - result = Either.left(property); - return result; - - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - private boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) { - boolean result = false; - if (!CollectionUtils.isEmpty(properties)) { - for (PropertyDefinition propertyDefinition : properties) { - - if ( propertyDefinition.getName().equals(propertyName) && - (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { - result = true; - break; - } - } - } - return result; - } - - private PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) { - log.debug("The object returned after create property is {}", propertyDataResult); - PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition()); - propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints())); - propertyDefResult.setName(propertyName); - propertyDefResult.setParentUniqueId(resourceId); - return propertyDefResult; - } - - private List<PropertyConstraint> convertConstraints(List<String> constraints) { - - if (constraints == null || constraints.size() == 0) { - return null; - } - - List<PropertyConstraint> list = new ArrayList<PropertyConstraint>(); - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - for (String constraintJson : constraints) { - PropertyConstraint propertyConstraint = gson.fromJson(constraintJson, constraintType); - list.add(propertyConstraint); - } - - return list; - } - - private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) { - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - return Either.right(validateAndUpdateProperty); - } - - return Either.left(newPropertyDefinition); - } - - private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) { - - log.trace("Going to validate property type and value. {}", propertyDefinition); - - String propertyType = propertyDefinition.getType(); - String value = propertyDefinition.getDefaultValue(); - - ToscaPropertyType type = getType(propertyType); - - if (type == null) { - - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (dataTypeDefinition == null) { - log.debug("The type {} of property cannot be found.", propertyType); - return StorageOperationStatus.INVALID_TYPE; - } - - StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); - - return status; - - } - String innerType = null; - - Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); - if (checkInnerType.isRight()) { - return StorageOperationStatus.INVALID_TYPE; - } - innerType = checkInnerType.left().value(); - - log.trace("After validating property type {}", propertyType); - - boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", value, type); - return StorageOperationStatus.INVALID_VALUE; - } - - PropertyValueConverter converter = type.getConverter(); - - if (isEmptyValue(value)) { - log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); - propertyDefinition.setDefaultValue(EMPTY_VALUE); - } else if (false == isEmptyValue(value)) { - String convertedValue = converter.convert(value, innerType, dataTypes); - propertyDefinition.setDefaultValue(convertedValue); - } - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, - - String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) { - - ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); - - if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); - return StorageOperationStatus.INVALID_VALUE; - } - - JsonElement jsonElement = validateResult.left; - - log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); - - updateValue(propertyDefinition, jsonElement); - - return StorageOperationStatus.OK; - } - - protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { - - propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); - - } - - protected String getValueFromJsonElement(JsonElement jsonElement) { - String value = null; - - if (jsonElement == null || jsonElement.isJsonNull()) { - value = EMPTY_VALUE; - } else { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - - return value; - } - - protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) { - String innerType = null; - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - - SchemaDefinition def = schemeGen.get();// propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - return Either.left(innerType); - } - protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (isEmptyValue(value)) { - return true; - } - - PropertyTypeValidator validator = type.getValidator(); - - boolean isValid = validator.isValid(value, innerType, dataTypes); - if (true == isValid) { - return true; - } else { - return false; - } - - } - - public boolean isEmptyValue(String value) { - if (value == null) { - return true; - } - return false; - } + private static final String CREATE_PROPERTY = "CreateProperty"; + + private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class); + + private static final String EMPTY_VALUE = null; + + private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() { + Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + return eitherAllDataTypes; + } + + /** + * Create new property on resource in graph + * + * @param resourceId + * @param propertyName + * @param newPropertyDefinition + * @param userId + * @return Either<PropertyDefinition, ActionStatus> + */ + public Either<EntryData<String, PropertyDefinition>, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { + + Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Property", false); + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + // Get the resource from DB + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + return result; + } + Resource resource = status.left().value(); + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return result; + } + + // verify property not exist in resource + List<PropertyDefinition> resourceProperties = resource.getProperties(); + + if (resourceProperties != null) { + if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); + return result; + } + } + + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + + Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + + // validate property default values + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + result = Either.right(defaultValuesValidation.right().value()); + return result; + } + // convert property + ToscaPropertyType type = getType(newPropertyDefinition.getType()); + if (type != null) { + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + if (newPropertyDefinition != null) { + SchemaDefinition schema = newPropertyDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newPropertyDefinition.getDefaultValue() != null) { + convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); + newPropertyDefinition.setDefaultValue(convertedValue); + } + } + } + + // add the new property to resource on graph + // need to get StorageOpaerationStatus and convert to ActionStatus + // from componentsUtils + Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + PropertyDefinition createdPropertyDefinition = either.left().value(); + EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition); + result = Either.left(property); + return result; + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + /** + * Get property of resource + * + * @param resourceId + * @param propertyId + * @param userId + * @return + */ + public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + // Get the resource from DB + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + // verify property exist in resource + List<PropertyDefinition> properties = resource.getProperties(); + if (properties == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); + } + for (PropertyDefinition property : properties) { + if (property.getUniqueId().equals(propertyId) ) { + Map<String, PropertyDefinition> propMap = new HashMap<>(); + propMap.put(property.getName(), property); + return Either.left(propMap.entrySet().iterator().next()); + } + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); + } + + /** + * delete property of resource from graph + * + * @param resourceId + * @param propertyId + * @param userId + * @return + */ + public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { + + Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null; + + Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + + // Get the resource from DB + Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId); + if (getResourceRes.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + return result; + } + Resource resource = getResourceRes.left().value(); + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return result; + } + + // verify property exist in resource + Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + if (statusGetProperty.isRight()) { + result = Either.right(statusGetProperty.right().value()); + return result; + } + + StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); + if (status != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); + return result; + } + result = Either.left(statusGetProperty.left().value()); + return result; + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + } + + /** + * update property + * + * @param resourceId + * @param propertyId + * @param newPropertyDefinition + * @param userId + * @return + */ + public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) { + + Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null; + + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + if (statusGetProperty.isRight()) { + result = Either.right(statusGetProperty.right().value()); + return result; + } + String propertyName = statusGetProperty.left().value().getKey(); + + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + + Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + result = Either.right(defaultValuesValidation.right().value()); + return result; + } + + Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes); + if (either.isRight()) { + log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + + either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value()); + result = Either.left(property); + return result; + + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + private boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) { + boolean result = false; + if (!CollectionUtils.isEmpty(properties)) { + for (PropertyDefinition propertyDefinition : properties) { + + if ( propertyDefinition.getName().equals(propertyName) && + (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { + result = true; + break; + } + } + } + return result; + } + + private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) { + + StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + return Either.right(validateAndUpdateProperty); + } + + return Either.left(newPropertyDefinition); + } + + private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) { + + log.trace("Going to validate property type and value. {}", propertyDefinition); + + String propertyType = propertyDefinition.getType(); + String value = propertyDefinition.getDefaultValue(); + + ToscaPropertyType type = getType(propertyType); + + if (type == null) { + + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (dataTypeDefinition == null) { + log.debug("The type {} of property cannot be found.", propertyType); + return StorageOperationStatus.INVALID_TYPE; + } + + StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); + + return status; + + } + String innerType = null; + + Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); + if (checkInnerType.isRight()) { + return StorageOperationStatus.INVALID_TYPE; + } + innerType = checkInnerType.left().value(); + + log.trace("After validating property type {}", propertyType); + + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (false == isValidProperty) { + log.info("The value {} of property from type {} is invalid", value, type); + return StorageOperationStatus.INVALID_VALUE; + } + + PropertyValueConverter converter = type.getConverter(); + + if (isEmptyValue(value)) { + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); + propertyDefinition.setDefaultValue(EMPTY_VALUE); + } else if (false == isEmptyValue(value)) { + String convertedValue = converter.convert(value, innerType, dataTypes); + propertyDefinition.setDefaultValue(convertedValue); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, + + String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) { + + ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + + if (validateResult.right.booleanValue() == false) { + log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); + return StorageOperationStatus.INVALID_VALUE; + } + + JsonElement jsonElement = validateResult.left; + + log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , jsonElement); + + updateValue(propertyDefinition, jsonElement); + + return StorageOperationStatus.OK; + } + + protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { + + propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); + + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } + + protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) { + String innerType = null; + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + + SchemaDefinition def = schemeGen.get(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + return Either.left(innerType); + } + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + boolean isValid = validator.isValid(value, innerType, dataTypes); + if (true == isValid) { + return true; + } else { + return false; + } + + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java index bd7e810066..6454379af8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java @@ -27,13 +27,13 @@ import org.springframework.stereotype.Component; @Component("requirementsBusinessLogic") public class RequirementsBusinessLogic { - private static Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class); - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index 4924bd25a7..f6cb50c5c2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -20,33 +20,15 @@ package org.openecomp.sdc.be.components.impl; -import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH; -import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; +import com.google.gson.Gson; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; @@ -59,7 +41,6 @@ import org.openecomp.sdc.be.components.merge.resource.MergeResourceBLFactory; import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -74,8 +55,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.info.ArtifactTemplateInfo; -import org.openecomp.sdc.be.info.MergedArtifactInfo; +import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; @@ -90,7 +70,6 @@ import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; @@ -113,7 +92,6 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; @@ -127,7 +105,7 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; @@ -138,7 +116,6 @@ import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; @@ -153,7288 +130,6634 @@ import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.parser.ParserException; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import javax.servlet.ServletContext; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; @org.springframework.stereotype.Component("resourceBusinessLogic") public class ResourceBusinessLogic extends ComponentBusinessLogic { - private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - public static final String INITIAL_VERSION = "0.1"; + private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; + public static final String INITIAL_VERSION = "0.1"; + + private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); + private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); + private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); + private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); + private Pattern GET_ATTRIBUTE_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_attribute" + "="); - private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); - private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); - private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); - private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class); - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName()); + private static Pattern pattern = Pattern.compile("\\..(.*?)\\.."); - private static Pattern pattern = Pattern.compile("\\..(.*?)\\.."); + /** + * Default constructor + */ + public ResourceBusinessLogic() { + log.debug("ResourceBusinessLogic started"); + } - /** - * Default constructor - */ - public ResourceBusinessLogic() { - log.debug("ResourceBusinessLogic started"); - } + @Autowired + private ICapabilityTypeOperation capabilityTypeOperation = null; - @Autowired - private ICapabilityTypeOperation capabilityTypeOperation = null; + @Autowired + private IInterfaceLifecycleOperation interfaceTypeOperation = null; - @Autowired - private IInterfaceLifecycleOperation interfaceTypeOperation = null; + @Autowired + private LifecycleBusinessLogic lifecycleBusinessLogic; - @Autowired - private LifecycleBusinessLogic lifecycleBusinessLogic; + @Autowired + private IPropertyOperation propertyOperation; - @Autowired - private IPropertyOperation propertyOperation; + @Autowired + private CsarOperation csarOperation; - @Autowired - private CsarOperation csarOperation; + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @Autowired - private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic; + @Autowired + private ResourceImportManager resourceImportManager; - @Autowired - private ResourceImportManager resourceImportManager; - @Autowired - private GroupBusinessLogic groupBusinessLogic; - - @Autowired - private InputsBusinessLogic inputsBusinessLogic; - - @Autowired - private CompositionBusinessLogic compositionBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private MergeResourceBLFactory mergeResourceBLFactory; + @Autowired + private InputsBusinessLogic inputsBusinessLogic; - private Gson gson = new Gson(); - - public CsarOperation getCsarOperation() { - return csarOperation; - } - - public void setCsarOperation(CsarOperation csarOperation) { - this.csarOperation = csarOperation; - } - - public LifecycleBusinessLogic getLifecycleBusinessLogic() { - return lifecycleBusinessLogic; - } - - public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { - this.lifecycleBusinessLogic = lifecycleBusinessLogic; - } - - public IElementOperation getElementDao() { - return elementDao; - } - - public void setElementDao(IElementOperation elementDao) { - this.elementDao = elementDao; - } - - public IUserBusinessLogic getUserAdmin() { - return this.userAdmin; - } - - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } - - public ComponentsUtils getComponentsUtils() { - return this.componentsUtils; - } - - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } - - public ArtifactsBusinessLogic getArtifactsManager() { - return artifactsBusinessLogic; - } - - public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { - this.artifactsBusinessLogic = artifactsManager; - } - - public void setPropertyOperation(IPropertyOperation propertyOperation) { - this.propertyOperation = propertyOperation; - } - - public ApplicationDataTypeCache getApplicationDataTypeCache() { - return applicationDataTypeCache; - } - - public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { - this.applicationDataTypeCache = applicationDataTypeCache; - } - - /** - * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param - * - * @param getAbstract - * @param userId TODO - * @return - */ - public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Boolean isHighest = null; - switch (highestFilter) { - case ALL: - break; - case HIGHEST_ONLY: - isHighest = true; - break; - case NON_HIGHEST_ONLY: - isHighest = false; - break; - default: - break; - } - Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest); - - if (getResponse.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value()))); - } - - return Either.left(getResponse.left().value()); - } - - public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map<String, Boolean> result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) { - Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false); - if (createResourceResponse.isRight()) { - return createResourceResponse; - } - - // Creating resource either by DAO or from CSAR - String csarUUID = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - } else { - csarUUID = payloadName; - } - if (csarUUID != null && !csarUUID.isEmpty()) { - // check if VF with the same Csar UUID or with he same name already - // exists - Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID); - if (validateCsarUuidUniquenessRes.isRight()) { - log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value()))); - } - - Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value(); - if (existingResourceRes.intValue() > 0) { - log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID); - componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null); - return Either.right(errorResponse); - } - - log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); - createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID); - return createResourceResponse; - } - - return createResourceByDao(resource, user, auditingAction, false, false, null); - } - - public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) { - Either<Resource, ResponseFormat> updateResourceResponse = null; - Either<Resource, ResponseFormat> validateResourceResponse = null; - Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>(); - String csarUUID = null; - String csarVersion = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - csarVersion = resource.getCsarVersion(); - } else { - csarUUID = payloadName; - } - if (csarUUID != null && !csarUUID.isEmpty()) { - Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId); - if (responseWrapper.isEmpty()) { - validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user); - } - if (responseWrapper.isEmpty()) { - validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user); - } - if (responseWrapper.isEmpty()) { - if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { - overrideImmutableMetadata(oldResource, resource); - } - validateResourceResponse = validateResourceBeforeCreate(resource, user, false); - if (validateResourceResponse.isRight()) { - responseWrapper.setInnerElement(validateResourceResponse.right().value()); - } - } - if (responseWrapper.isEmpty()) { - String oldCsarVersion = oldResource.getCsarVersion(); - log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId); - // (on boarding flow): If the update includes same csarUUID and - // same csarVersion as already in the VF - no need to import the - // csar (do only metadata changes if there are). - if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { - updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false); - } else { - updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID); - } - } - } else { - log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - responseWrapper.setInnerElement(errorResponse); - } - if (responseWrapper.isEmpty()) { - return updateResourceResponse; - } - return Either.right(responseWrapper.getInnerElement()); - } - - private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) { - // (on boarding flow): If the update includes a csarUUID: verify this - // csarUUID is not in use by another VF, If it is - use same error as - // above: - // "Error: The VSP with UUID %1 was already imported for VF %2. Please - // select another or update the existing VF." %1 - csarUUID, %2 - VF - // name - Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); - if (resourceLinkedToCsarRes.isRight()) { - if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { - log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName()); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value()))); - } - } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null); - responseWrapper.setInnerElement(errorResponse); - } - } - - private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) { - // (on boarding flow): If the update includes csarUUID which is - // different from the csarUUID of the VF - fail with - // error: "Error: Resource %1 cannot be updated using since it is linked - // to a different VSP" %1 - VF name - String oldCsarUUID = oldResource.getCsarUUID(); - if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { - log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null); - responseWrapper.setInnerElement(errorResponse); - } - } - - private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) { - Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId); - if (oldResourceRes.isRight()) { - log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value()); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value()))); - return null; - } - return oldResourceRes.left().value(); - } - - private void overrideImmutableMetadata(Resource oldRresource, Resource resource) { - resource.setName(oldRresource.getName()); - resource.setIcon(oldRresource.getIcon()); - resource.setTags(oldRresource.getTags()); - resource.setVendorName(oldRresource.getVendorName()); - resource.setCategories(oldRresource.getCategories()); - resource.setDerivedFrom(oldRresource.getDerivedFrom()); - } - - private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, - String csarUUID) { - - // check state - if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) { - if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) { - log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - String lockedResourceId = oldRresource.getUniqueId(); - List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); - - Either<Map<String, byte[]>, StorageOperationStatus> csar = null; - if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { - csar = csarUIPayload; - } else { - csar = csarOperation.getCsar(csarUUID, user); - } - if (csar.isRight()) { - log.debug("Failed to get csar for casrUUID{} ", csarUUID); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value()))); - } - - Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar); - if (toscaYamlCsarStatus.isRight()) { - return Either.right(toscaYamlCsarStatus.right().value()); - } - Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils); - if (checksum.isRight()) { - log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value()); - return Either.right(checksum.right().value()); - } - boolean isUpdateYaml = true; - if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) { - log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value()); - if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) - isUpdateYaml = false; - } else { - oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value()); - } - - Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - - String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); - String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); - CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, true); - Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo); - Either<Resource, ResponseFormat> result = null; - - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, oldRresource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); - result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); - return result; - } - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value(); - try{ - result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); - - } finally { - if (result == null || result.isRight()) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - return result; - - } - - private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts, - boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, String nodeName, boolean isNested) { - Either<Resource, ResponseFormat> result; - Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither; - boolean inTransaction = true; - boolean shouldLock = false; - - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate; - Resource preparedResource; - Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName); - if (uploadComponentInstanceInfoMap.isRight()) { - ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - - Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances(); - - if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) { - - prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock, isNested); - if (prepareForUpdate.isRight()) { - log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); - result = Either.right(prepareForUpdate.right().value()); - return result; - } - preparedResource = prepareForUpdate.left().value().left; - - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); - - Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource); - if (genericResourceEither.isRight()) { - log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value()); - ResponseFormat responseFormat = genericResourceEither.right().value(); - componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - return Either.right(responseFormat); - } - - parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); - if (parseNodeTypeInfoYamlEither.isRight()) { - ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - - Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); - Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, csarInfo.getModifier(), inputs, inTransaction); - if (createInputsOnResource.isRight()) { - log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value()); - ResponseFormat responseFormat = createInputsOnResource.right().value(); - componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - preparedResource = createInputsOnResource.left().value(); - - Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, csarInfo.getCreatedNodes()); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); - ResponseFormat responseFormat = createResourcesInstancesEither.right().value(); - componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - preparedResource = createResourcesInstancesEither.left().value(); - - createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value()); - result = Either.right(createResourcesInstancesEither.right().value()); - return result; - } - - preparedResource = createResourcesInstancesEither.left().value(); - - Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { - - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - // add groups to resource - Map<String, GroupDefinition> groups; - - if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left().value(); - } else { - groups = uploadComponentInstanceInfoMap.left().value().getGroups(); - } - Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, csarInfo.getModifier(), groups); - if (updatedGroupsOnResource.isRight()) { - - return updatedGroupsOnResource; - } - preparedResource = updatedGroupsOnResource.left().value(); - - } else { - Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, csarInfo.getModifier(), oldRresource, shouldLock, inTransaction); - if (dataModelResponse.isRight()) { - log.debug("failed to update resource metadata {}", dataModelResponse.right().value()); - result = Either.right(dataModelResponse.right().value()); - return result; - } - preparedResource = dataModelResponse.left().value(); - } - - if(preparedResource.getResourceType() == ResourceTypeEnum.CVFC){ - if(nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()){ - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - } else { - Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), shouldLock, inTransaction); - log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); - if (createdCsarArtifactsEither.isRight()) { - return createdCsarArtifactsEither; - } - preparedResource = createdCsarArtifactsEither.left().value(); - } - - ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource); - if (mergingPropsAndInputsStatus != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource); - return Either.right(responseFormat); - } - - Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); - result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource); - - return result; - - } - - private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { - Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory.getInstance(oldResource, newResource); - if (mergeResourceBLEither.isRight()) { - return mergeResourceBLEither.right().value(); - } - MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value(); - return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource); - } - - private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) { - Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource); - if (genericResourceEither.isRight()) { - return genericResourceEither; - } - if (resource.shouldGenerateInputs()) { - generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); - } - return genericResourceEither; - } - - private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { - - Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes; - - try { - nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - Map<String, ImmutablePair<String,String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); - Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes; - EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null; - log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID()); - - for (Entry<String, ImmutablePair<String,String>> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) { - String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft(); - String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight(); - String currNamespace = currVfcToscaNameEntry.getKey(); - log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName); - - Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName); - Resource curNodeType = null; - if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { - curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName); - } - if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { - log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarInfo.getCsarUUID()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - break; - } else if (curVfcRes.isLeft()) { - curNodeType = curVfcRes.left().value(); - } - if (!MapUtils.isEmpty(extractedVfcsArtifacts)) { - List<ArtifactDefinition> currArtifacts = new ArrayList<>(); - if (extractedVfcsArtifacts.containsKey(currNamespace)) { - handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace)); - } - curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); - if (curNodeTypeArtifactsToHandleRes.isRight()) { - nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value()); - break; - } - curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value(); - - } else if (curNodeType != null) { - // delete all artifacts if have not received artifacts from csar - curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); - // delete all informational artifacts - artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList())); - // delete all deployment artifacts - artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); - if (!artifactsToDelete.isEmpty()) { - curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - } - if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) { - nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle); - } - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); - } - return nodeTypesArtifactsToHandleRes; - } - - private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) { - - Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null; - EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - try { - List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts); - List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>(); - List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); - if (curNodeType != null) { - Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>(); - if (curNodeType.getDeploymentArtifacts() != null) { - existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); - } - if (curNodeType.getArtifacts() != null) { - existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); - } - for (ArtifactDefinition currNewArtifact : extractedArtifacts) { - ArtifactDefinition foundArtifact; - - if (!existingArtifacts.isEmpty()) { - foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); - if (foundArtifact != null) { - if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - foundArtifact.setPayload(currNewArtifact.getPayloadData()); - foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); - foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); - artifactsToUpdate.add(foundArtifact); - } - existingArtifacts.remove(foundArtifact.getArtifactLabel()); - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - break; - } - } - } - } - if (responseWrapper.isEmpty()) { - artifactsToDelete.addAll(existingArtifacts.values()); - } - } - if (responseWrapper.isEmpty()) { - if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { - nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - if (!artifactsToUpload.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); - if (!artifactsToUpdate.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); - if (!artifactsToDelete.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); - } - if (!responseWrapper.isEmpty()) { - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - } - return nodeTypeArtifactsToHandleRes; - } - - /** - * Changes resource life cycle state to checked out - * - * @param resource - * @param user - * @param inTransaction - * @return - */ - private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) { - Either<Resource, ResponseFormat> checkoutResourceRes; - try { - if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName()); - Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus()); - checkoutResourceRes = Either.right(checkoutRes.right().value()); - } else { - checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); - } - } else { - checkoutResourceRes = Either.left(resource); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - checkoutResourceRes = Either.right(responseFormat); - log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e); - } - return checkoutResourceRes; - } - - /** - * Handles Artifacts of NodeType - * - * @param nodeTypeResource - * @param nodeTypeArtifactsToHandle - * @param vfcsNewCreatedArtifacts - * @param user - * @param inTransaction - * @return - */ - public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, - User user, boolean inTransaction, boolean ignoreLifecycleState) { - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes; - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null; - Either<Resource, ResponseFormat> changeStateResponse; - try { - changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); - if (changeStateResponse.isRight()) { - return Either.right(changeStateResponse.right().value()); - } - nodeTypeResource = changeStateResponse.left().value(); - - List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>(); - log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); - for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) { - ArtifactOperationEnum curOperation = curOperationEntry.getKey(); - List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue(); - if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { - log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName()); - handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts, - artifactsBusinessLogic.new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction); - if (handleNodeTypeArtifactsRequestRes.isRight()) { - handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); - break; - } - if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { - createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - } - if (handleNodeTypeArtifactsRes == null) { - handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleNodeTypeArtifactsRes = Either.right(responseFormat); - log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); - } - return handleNodeTypeArtifactsRes; - } - - private Map<String, ImmutablePair<String,String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) { - Map<String, ImmutablePair<String,String>> vfcToscaNames = new HashMap<>(); - - Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo); - if (!nodes.isEmpty()) { - Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator(); - while (nodesNameEntry.hasNext()) { - Entry<String, Object> nodeType = nodesNameEntry.next(); - ImmutablePair<String,String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); - vfcToscaNames.put(nodeType.getKey(), toscaResourceName); - } - } - for(NodeTypeInfo cvfc : nodeTypesInfo.values()){ - vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); - } - return vfcToscaNames; - } - - private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) { - Map<String, Object> nodes = new HashMap<>(); - for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){ - extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); - } - extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); - return nodes; - } - - private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) { - Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (eitherNodeTypes.isLeft()) { - nodes.putAll(eitherNodeTypes.left().value()); - } - } - - public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) { - log.trace("************* created successfully from YAML, resource TOSCA "); - - Either<Map<String, byte[]>, StorageOperationStatus> csar = null; - if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { - csar = csarUIPayload; - } else { - csar = csarOperation.getCsar(csarUUID, user); - } - - Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar); - if (toscaYamlCsarStatus.isRight()) { - return Either.right(toscaYamlCsarStatus.right().value()); - } - Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils); - if (toscaYamlChecksum.isRight()) { - log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value()); - return Either.right(toscaYamlChecksum.right().value()); - } - resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value()); - - String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); - String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); - - CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false); - Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo); - Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); - return Either.right(findNodeTypesArtifactsToHandleRes.right().value()); - } - Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null); - if (createResourceFromYaml.isRight()) { - log.debug("Couldn't create resource from YAML"); - return Either.right(createResourceFromYaml.right().value()); - } - - Resource vfResource = createResourceFromYaml.left().value(); - log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName()); - return Either.left(vfResource); - } - - private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) { - Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>(); - List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>(); - for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) { - extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry); - } - if (CollectionUtils.isNotEmpty(globalSubstitutes)) { - setDerivedFrom(nodeTypesInfo, globalSubstitutes); - } - markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo); - return nodeTypesInfo; - } - - @SuppressWarnings("unchecked") - private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Entry<String, byte[]>> globalSubstitutes) { - for (Map.Entry<String, byte[]> entry : globalSubstitutes) { - String yamlFileContents = new String(entry.getValue()); - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents); - Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); - if (nodeTypesEither.isLeft()) { - Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value(); - for (Entry<String, Object> nodeType : nodeTypes.entrySet()) { - Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue(); - if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) { - if (nodeTypesInfo.containsKey(nodeType.getKey())) { - NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey()); - List<String> derivedFrom = new ArrayList<>(); - derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName())); - nodeTypeInfo.setDerivedFrom(derivedFrom); - } - } - } - } - } - } - - @SuppressWarnings("unchecked") - private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo, - List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) { - if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) { - if (!isGlobalSubstitute(entry.getKey())) { - String yamlFileContents = new String(entry.getValue()); - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents); - Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP); - if (substitutionMappingsEither.isLeft()) { - Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value(); - if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) { - NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); - nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName())); - nodeTypeInfo.setTemplateFileName(entry.getKey()); - nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate); - nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo); - } - } - } else { - globalSubstitutes.add(entry); - } - } - } - - - @SuppressWarnings("unchecked") - private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) { - Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP); - if (nodeTemplatesEither.isLeft()) { - Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value(); - for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) { - Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue(); - if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (nodeTypesInfo.containsKey(type)) { - NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); - nodeTypeInfo.setNested(true); - } - } - } - } - } - - private boolean isGlobalSubstitute(String fileName) { - return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); - } - - private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) { - if (csar.isRight()) { - StorageOperationStatus value = csar.right().value(); - log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils); - if (validateCsarStatus.isRight()) { - ResponseFormat responseFormat = validateCsarStatus.right().value(); - log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - - Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils); - - if (toscaYamlCsarStatus.isRight()) { - ResponseFormat responseFormat = toscaYamlCsarStatus.right().value(); - log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - return toscaYamlCsarStatus; - } - - private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { - log.trace("validating resource before create"); - Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user.copyData(eitherCreator.left().value()); - - // validate user role - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - // VF / PNF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(resource)) { - Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - } - return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); - - } -//resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null - private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { - - List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>(); - log.trace("************* createResourceFromYaml before parse yaml "); - Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - log.trace("************* createResourceFromYaml after parse yaml "); - ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value(); - log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo); - log.trace("************* createResourceFromYaml before create "); - Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, - AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, - nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); - log.trace("************* createResourceFromYaml after create "); - if (createdResourceResponse.isRight()) { - ResponseFormat responseFormat = createdResourceResponse.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - return createdResourceResponse; - - } - - public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) { - - Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - if (tosca_version.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - return Either.right(responseFormat); - } - Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); - Map<String, Object> mapToConvert = new HashMap<String, Object>(); - mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value()); - Resource vfcCreated = null; - if (eitherNodeTypes.isLeft()) { - Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry<String, Object> nodeType = nodesNameValue.next(); - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey()); - - if (nodeTypesInfo.containsKey(nodeType.getKey())) { - log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); - Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey()); - log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - if (handleNeatedVfcYaml.isRight()) { - return Either.right(handleNeatedVfcYaml.right().value()); - } - vfcCreated = handleNeatedVfcYaml.left().value(); - } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){ - log.trace("************* Going to create node {}", nodeType.getKey()); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); - log.debug("************* Finished to create node {}", nodeType.getKey()); - - if (resourceCreated.isRight()) { - return Either.right(resourceCreated.right().value()); - } - vfcCreated = resourceCreated.left().value().getLeft(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName()); - } - if (vfcCreated != null) { - csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); - } - mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName()); - } - } - return result; - } - - private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, - List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName) { - - Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource); - String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); - Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - - log.debug("************* Going to create node types from yaml {}", yamlName); - Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource, - nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); - if (createNodeTypesRes.isRight()) { - log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value()); - return Either.right(createNodeTypesRes.right().value()); - } - log.debug("************* Finished to create node types from yaml {}", yamlName); - - if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { - log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); - } - return handleNestedVfcRes; - } - - private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, - Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) { - - Either<Resource, ResponseFormat> result = null; - Resource oldComplexVfc = null; - Resource newComplexVfc = null; - - Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); - if(buildCvfcRes.isRight()){ - log.debug("Failed to validate complex VFC for node {}. ", nodeName); - result = buildCvfcRes; - } - if(result == null){ - newComplexVfc = buildCvfcRes.left().value(); - Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); - if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND){ - oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight()); - } - if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){ - log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } else if(oldComplexVfcRes.isLeft()){ - log.debug("validate derived before update"); - Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); - if (eitherValidation.isLeft()) { - oldComplexVfc = oldComplexVfcRes.left().value(); - } - } - } - if(result == null){ - result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc); - } - if(result.isLeft()){ - newComplexVfc = result.left().value(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); - log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); - result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true); - if (result.isRight()) { - log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName()); - } - } - if(result.isLeft()){ - csarInfo.getCreatedNodes().put(nodeName, result.left().value()); - csarInfo.getCvfcToCreateQueue().remove(); - } - return result; - } - - private Either<Resource, ResponseFormat> handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, - CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { - - Either<Resource, ResponseFormat> handleComplexVfcRes; - Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); - String yamlContent = new String(csarInfo.getCsar().get(yamlName)); - Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy())); - markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); - if(oldComplexVfc == null){ - handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName); - if (handleComplexVfcRes.isRight()) { - log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName); - } - } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); - if (handleComplexVfcRes.isRight()) { - log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName); - } - } - return handleComplexVfcRes; - } - - private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) { - - Either<Resource, ResponseFormat> result = null; - Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); - log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); - - if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){ - csarInfo.getCvfcToCreateQueue().add(nodeName); - } else { - log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName())); - } - if(result == null){ - result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); - if(result.isRight()){ - log.debug("Failed to validate complex VFC {}. ", complexVfc.getName()); - } - } - return result; - } - - private String getNodeTypeActualName(String fullName) { - String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - return nameWithouNamespacePrefix.substring(resourceType.length()); - } - - private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock, - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, boolean isNested) { - - Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - if (resourceMetaData.isRight()) { - return Either.right(resourceMetaData.right().value()); - } - String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo); - - Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); - } - - private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, CsarInfo csarInfo) { - // We need to create a Yaml from each node_types in order to create - // resource from each node type using import normative flow. - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - - Map<String, Object> node = new HashMap<>(); - node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), nodeNameValue.getValue()); - mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); - - return yaml.dumpAsMap(mapToConvert); - } - - public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) { - - Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - return Either.left(true); - } - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, - Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); - Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator); - return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); - } - - private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) { - UploadResourceInfo resourceMetaData = new UploadResourceInfo(); - - // validate nodetype name prefix - if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { - log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); - return Either.right(responseFormat); - } - - String actualName = this.getNodeTypeActualName(nodeName); - String namePrefix = nodeName.replace(actualName, ""); - String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - - // if we import from csar, the node_type name can be - // org.openecomp.resource.abstract.node_name - in this case we always - // create a vfc - if (resourceType.equals(Constants.ABSTRACT)) { - resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); - } - // validating type - if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { - log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); - return Either.right(responseFormat); - } - - // Setting name - resourceMetaData.setName(resourceVf.getSystemName() + actualName); - - // Setting type from name - String type = resourceType.toUpperCase(); - resourceMetaData.setResourceType(type); - - resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); - resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); - resourceMetaData.setContactId(user.getUserId()); - resourceMetaData.setVendorName(resourceVf.getVendorName()); - resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); - - // Setting tag - List<String> tags = new ArrayList<>(); - tags.add(resourceMetaData.getName()); - resourceMetaData.setTags(tags); - - // Setting category - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - resourceMetaData.setCategories(categories); - - return Either.left(resourceMetaData); - } - - private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) { - Resource cvfc = new Resource(); - NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); - cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); - cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); - cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); - cvfc.setResourceType(ResourceTypeEnum.CVFC); - cvfc.setAbstract(true); - cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); - cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); - cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); - cvfc.setContactId(csarInfo.getModifier().getUserId()); - cvfc.setCreatorUserId(csarInfo.getModifier().getUserId()); - cvfc.setVendorName(resourceVf.getVendorName()); - cvfc.setVendorRelease(resourceVf.getVendorRelease()); - cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft()); - cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - - List<String> tags = new ArrayList<>(); - tags.add(cvfc.getName()); - cvfc.setTags(tags); - - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List<CategoryDefinition> categories = new ArrayList<>(); - categories.add(category); - cvfc.setCategories(categories); - - cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); - cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); - cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - - return cvfc; - } - - private String buildCvfcName(String resourceVfName, String nodeName) { - String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); - return addCvfcSuffixToResourceName(resourceName); - } - - private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, - List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, - CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { - - boolean result = true; - List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>(); - - if (shouldLock) { - Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - return Either.right(responseFormat); - } - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - log.trace("************* createResourceFromYaml before full create resource {}", yamlName); - Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource); - if (genericResourceEither.isRight()) { - result = false; - return genericResourceEither; - } - Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction); - log.trace("************* createResourceFromYaml after full create resource {}", yamlName); - if (createResourcesEither.isRight()) { - result = false; - return createResourcesEither; - } - resource = createResourcesEither.left().value(); - // add groups to resource - log.trace("************* Going to add inputs from yaml {}", yamlName); - if (resource.shouldGenerateInputs()) - generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); - - Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs(); - Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction); - if (createInputsOnResource.isRight()) { - result = false; - return createInputsOnResource; - } - resource = createInputsOnResource.left().value(); - log.trace("************* Finish to add inputs from yaml {}", yamlName); - - Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); - log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); - - createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); - log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); - if (createResourcesEither.isRight()) { - result = false; - return createResourcesEither; - } - - resource = createResourcesEither.left().value(); - // validate update vf module group names - Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { - result = false; - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - // add groups to resource - Map<String, GroupDefinition> groups; - log.trace("************* Going to add groups from yaml {}", yamlName); - - if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left().value(); - } else { - groups = parsedToscaYamlInfo.getGroups(); - } - Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups); - if (createGroupsOnResource.isRight()) { - result = false; - return createGroupsOnResource; - } - resource = createGroupsOnResource.left().value(); - log.trace("************* Finished to add groups from yaml {}", yamlName); - - log.trace("************* Going to add artifacts from yaml {}", yamlName); - - if(resource.getResourceType() == ResourceTypeEnum.CVFC){ - if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){ - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - } else { - Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false, - inTransaction); - log.trace("************* Finished to add artifacts from yaml {}", yamlName); - if (createdCsarArtifactsEither.isRight()) { - result = false; - return createdCsarArtifactsEither; - } - resource = createdCsarArtifactsEither.left().value(); - } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null); - ASDCKpiApi.countCreatedResourcesKPI(); - return Either.left(resource); - - } finally { - if (!inTransaction) { - if (!result) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { - createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); - log.debug("component and all its artifacts were deleted, id = {}", resource.getName()); - } - - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - if (shouldLock) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - } - - private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) { - if (groups != null && !groups.isEmpty()) { - Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource); - - if (mergeGroupsUsingResource.isRight()) { - log.debug("Failed to prepare groups for creation"); - return Either.right(mergeGroupsUsingResource.right().value()); - } - List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value(); - Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); - } - } else { - return Either.left(resource); - } - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) { - if (groups != null && false == groups.isEmpty()) { - List<GroupDefinition> groupsFromResource = resource.getGroups(); - Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource); - - if (mergeGroupsUsingResource.isRight()) { - log.debug("Failed to prepare groups for creation"); - return Either.right(mergeGroupsUsingResource.right().value()); - } - List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value(); - List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>(); - List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>(); - List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>(); - if (groupsFromResource != null && !groupsFromResource.isEmpty()) { - for (GroupDefinition group : groupsAsList) { - Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); - if (op.isPresent()) { - GroupDefinition groupToUpdate = op.get(); - groupToUpdate.setMembers(group.getMembers()); - groupsToUpdate.add(groupToUpdate); - } else { - groupsToCreate.add(group); - } - } - for (GroupDefinition group : groupsFromResource) { - Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); - if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { - - groupsToDelete.add(group); - } - - } - } else - groupsToCreate.addAll(groupsAsList); - Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null; - if (!groupsToCreate.isEmpty()) { - - if (groupsFromResource != null && !groupsFromResource.isEmpty()) { - prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); - } else { - prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); - } - - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - if (!groupsToDelete.isEmpty()) { - prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { - prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - } else { - return Either.left(resource); - } - - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) { - List<InputDefinition> resourceProperties = resource.getInputs(); - if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) { - - Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); - if (createInputs.isRight()) { - return Either.right(createInputs.right().value()); - } - } else { - return Either.left(resource); - } - - Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) { - - List<GroupDefinition> result = new ArrayList<>(); - - List<ComponentInstance> componentInstances = component.getComponentInstances(); - - if (groups != null) { - Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); - if (validateCyclicGroupsDependencies.isRight()) { - return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies); - } - for (Entry<String, GroupDefinition> entry : groups.entrySet()) { - String groupName = entry.getKey(); - - GroupDefinition groupDefinition = entry.getValue(); - - GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); - updatedGroupDefinition.setMembers(null); - - // get the members of the group - Map<String, String> members = groupDefinition.getMembers(); - if (members != null) { - Set<String> compInstancesNames = members.keySet(); - - if (componentInstances == null || true == componentInstances.isEmpty()) { - String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); - } - // Find all component instances with the member names - Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); - memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> ""))); - Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue())); - - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { - - List<String> foundMembers = new ArrayList<>(); - if (relevantInstances != null) { - foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList()); - } - compInstancesNames.removeAll(foundMembers); - String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); - } - - updatedGroupDefinition.setMembers(relevantInstances); - } - - result.add(updatedGroupDefinition); - } - } - return Either.left(result); - } - - /** - * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A - * - * @param allGroups - * @return - */ - private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) { - - Either<Boolean, ResponseFormat> result = Either.left(true); - try { - Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator(); - while (allGroupsItr.hasNext() && result.isLeft()) { - Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next(); - // Fetches a group member A - String groupAName = groupAEntry.getKey(); - // Finds all group members in group A - Set<String> allGroupAMembersNames = new HashSet<>(); - fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); - // If A is a group member of itself found cyclic dependency - if (allGroupAMembersNames.contains(groupAName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); - result = Either.right(responseFormat); - } - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - result = Either.right(responseFormat); - log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); - } - return result; - } - - /** - * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group. - * - * @param groupName - * @param allGroups - * @param allGroupMembers - * @return - */ - private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) { - - // Found Cyclic dependency - if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { - return; - } - GroupDefinition groupDefinition = allGroups.get(groupName); - // All Members Of Current Group Resource Instances & Other Groups - Set<String> currGroupMembers = groupDefinition.getMembers().keySet(); - // Filtered Members Of Current Group containing only members which - // are groups - List<String> currGroupFilteredMembers = currGroupMembers.stream(). - // Keep Only Elements of type group and not Resource Instances - filter(innerGroupName -> allGroups.containsKey(innerGroupName)). - // Add Filtered Elements to main Set - peek(innerGroupName -> allGroupMembers.add(innerGroupName)). - // Collect results - collect(Collectors.toList()); - - // Recursively call the method for all the filtered group members - for (String innerGroupName : currGroupFilteredMembers) { - fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); - } - - } - - private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) { - - boolean stop = false; - // In Case Not Group Stop - if (!allGroups.containsKey(groupName)) { - stop = true; - } - // In Case Group Has no members stop - if (!stop) { - GroupDefinition groupDefinition = allGroups.get(groupName); - stop = MapUtils.isEmpty(groupDefinition.getMembers()); - - } - // In Case all group members already contained stop - if (!stop) { - final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet(); - Set<String> membersOfTypeGroup = allMembers.stream(). - // Filter In Only Group members - filter(innerGroupName -> allGroups.containsKey(innerGroupName)). - // Collect - collect(Collectors.toSet()); - stop = allGroupMembers.containsAll(membersOfTypeGroup); - } - return stop; - } - - private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum, - String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, - String nodeName) { - - Either<Resource, ResponseFormat> result; - Either<Resource, ResponseFormat> createResourcesInstancesEither; - - log.debug("************* Going to create all nodes {}", yamlName); - Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName); - log.debug("************* Finished to create all nodes {}", yamlName); - if (createdResourcesFromdNodeTypeMap.isRight()) { - log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value()); - return Either.right(createdResourcesFromdNodeTypeMap.right().value()); - } - - log.debug("************* Going to create all resource instances {}", yamlName); - createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes()); - - log.debug("************* Finished to create all resource instances {}", yamlName); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); - result = createResourcesInstancesEither; - return createResourcesInstancesEither; - } - resource = createResourcesInstancesEither.left().value(); - log.debug("************* Going to create all relations {}", yamlName); - createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap); - - log.debug("************* Finished to create all relations {}", yamlName); - - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value()); - result = createResourcesInstancesEither; - return result; - } else { - resource = createResourcesInstancesEither.left().value(); - } - - log.debug("************* Going to create positions {}", yamlName); - Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); - log.debug("************* Finished to set positions {}", yamlName); - result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource); - - return result; - } - - private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) { - List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList()); - artifactsToAdd.stream().forEach(a -> { - if (!vfcArtifactNames.contains(a.getArtifactName())) { - vfcArtifacts.add(a); - } else { - log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName()); - } - }); - - } - - @SuppressWarnings("unchecked") - private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, - Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, - Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName) { - - Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); - for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) { - if (nodeTypeEntry.getValue().isNested()) { - - Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); - log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); - if (createResourceFromYaml.isRight()) { - return Either.right(createResourceFromYaml.right().value()); - } - } - } - - Map<String, Object> mappedToscaTemplate = null; - if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){ - mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); - } - if(MapUtils.isEmpty(mappedToscaTemplate)){ - mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml); - } - - Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); - if (createdNodeTypeFromMainTemplateEither.isRight()) { - ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - // add the created node types to the cache although they are not in the - // graph. - csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource)); - - return result; - } - - private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, - boolean inTransaction) { - - if (csarInfo.getCsar() != null) { - String vendorLicenseModelId = null; - String vfLicenseModelId = null; - - if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) { - Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts(); - if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { - for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) { - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) - vendorLicenseModelId = artifactEntry.getValue().getUniqueId(); - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) - vfLicenseModelId = artifactEntry.getValue().getUniqueId(); - } - } - - } - // Specific Behavior for license artifacts - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction); - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction); - - Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); - if (eitherCreateResult.isRight()) { - return Either.right(eitherCreateResult.right().value()); - } - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - resource = eitherGerResource.left().value(); - - Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); - if (artifacsMetaCsarStatus.isLeft()) { - - String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); - String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); - Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource); - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) - createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - else - createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - if (createArtifactsFromCsar.isRight()) { - log.debug("Couldn't create artifacts from artifacts.meta"); - return Either.right(createArtifactsFromCsar.right().value()); - } - - resource = createArtifactsFromCsar.left().value(); - } else { - List<GroupDefinition> groupsToDelete = resource.getGroups(); - - if (groupsToDelete != null && !groupsToDelete.isEmpty()) { - Set<String> artifactsToDelete = new HashSet<String>(); - - for (String artifactId : artifactsToDelete) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, - resource, null, null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - log.debug("Couldn't delete artifact {}", artifactId); - return Either.right(handleDelete.right().value()); - } - } - Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - - return Either.right(responseFormat); - - } - resource = eitherGetResource.left().value(); - } - } - } - return Either.left(resource); - } - - private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType, - ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, - boolean inTransaction) { - byte[] artifactFileBytes = null; - - if (csarInfo.getCsar().containsKey(artifactPath)) { - artifactFileBytes = csarInfo.getCsar().get(artifactPath); - } - Either<Boolean, ResponseFormat> result = Either.left(true); - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) { - if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, - null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - result = Either.right(handleDelete.right().value()); - } - return result; - } - - if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) { - operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create); - } - - } - if (artifactFileBytes != null) { - Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction); - addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); - if (eitherNonMetaArtifacts.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING); - return Either.right(eitherNonMetaArtifacts.right().value()); - } - } - return result; - } - - private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) { - Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value(); - if (eitherResult.isLeft()) { - createdArtifacts.add(eitherResult.left().value()); - } - } - } - - private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) { - - String jsonStr = gson.toJson(json); - - String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr); - ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class); - String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId, - artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false); - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - return Either.left(uploadArtifactToService.left().value()); - } - - public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts, - boolean shouldLock, boolean inTransaction) { - - Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - List<GroupDefinition> groups = resource.getGroups(); - Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts(); - List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>(); - if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { - for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) { - createdDeplymentArtifactsAfterDelete.add(entry.getValue()); - } - } - int labelCounter = createdDeplymentArtifactsAfterDelete.size(); - - if (deplymentArtifact == null || deplymentArtifact.isEmpty()) { - if (groups != null && !groups.isEmpty()) { - for (GroupDefinition group : groups) { - if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) { - log.debug("failed to update artifacts from csar. List of emty but group not empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } - } - return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction); - } - - // find master in group - Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact); - - ////////////////////////////////////// create set parsed - ////////////////////////////////////// artifacts/////////////////////////////////////////// - Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); - - Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>(); - List<ArtifactTemplateInfo> artifactsWithoutGroups = null; - if(parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)){ - artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT); - parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); - } - Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values(); - for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - if(parsedGroupTemplate.getGroupName() != null){ - parsedGroupTemplate.setGroupName(""); - Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>(); - parsedArtifactsNames.add(parsedGroupTemplate); - List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { - createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames); - } - parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames); - }else{ - List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>(); - arrtifacts.add(parsedGroupTemplate); - Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - - } - } - - } - - ///////////////////////////////// find artifacts to - ///////////////////////////////// delete//////////////////////////////////////////////////// - - Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>(); - Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>(); - - Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet(); - Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete); - - // Set<String> deletedArtifactsName = new HashSet<String>(); - Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete); - if (deletedArtifactsEither.isRight()) { - log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value()); - - return Either.right(deletedArtifactsEither.right().value()); - - } - List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value(); - - // need to update resource if we updated artifacts - if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) { - for (ArtifactDefinition deletedArtifact : deletedArtifacts) { - ArtifactDefinition artToRemove = null; - for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) { - if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) { - artToRemove = artFromResource; - break; - } - } - if (artToRemove != null) - createdDeplymentArtifactsAfterDelete.remove(artToRemove); - - } - } - - ////////////// dissociate, associate or create - ////////////// artifacts//////////////////////////// - Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete, - mergedgroup, deletedArtifacts); - groups = resource.getGroups(); - if (assDissotiateEither.isRight()) { - log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value()); - - return Either.right(assDissotiateEither.right().value()); - - } - resource = assDissotiateEither.left().value(); - deplymentArtifact = resource.getDeploymentArtifacts(); - createdDeplymentArtifactsAfterDelete.clear(); - if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { - for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) { - createdDeplymentArtifactsAfterDelete.add(entry.getValue()); - } - } - - - - // update vfModule names - Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet(); - if (groups != null && !groups.isEmpty()) { - Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction); - if (validateUpdateVfGroupNamesRes.isRight()) { - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - List<GroupDefinition> heatGroups = null; - - heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - ; - - for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) { - - if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) { - updatedGroupDef.getMembers().clear(); - } - Map<String, String> members = new HashMap<String, String>(); - Set<String> artifactsGroup = new HashSet<String>(); - artifactsGroup.addAll(updatedGroupDef.getArtifacts()); - associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members); - if (!members.isEmpty()) { - updatedGroupDef.setMembers(members); - - } - - - } - - - } - - //////////////// create new artifacts in update - //////////////// flow//////////////////////////// - List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>(); - - for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) { - ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey(); - boolean isNewGroup = true; - for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) { - Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue(); - Set<ArtifactDefinition> group = groupArtifacts.keySet(); - for (ArtifactDefinition artifactInfo : group) { - if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) { - parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName()); - isNewGroup = false; - } - } - } - if (isNewGroup) - newArtifactsGroup.add(parsedArtifactMaster); - - } - if (!newArtifactsGroup.isEmpty()) { - Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); - int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups); - Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter); - if (validateGroupNamesRes.isRight()) { - return Either.right(validateGroupNamesRes.right().value()); - } - Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - - // updatedGroup - if (!groupForAssociateWithMembers.isEmpty()) { - - List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList()); - - Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId); - if (updateVersionEither.isRight()) { - log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); - - return Either.right(updateVersionEither.right().value()); - - } - } - if(artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()){ - for(ArtifactTemplateInfo t: artifactsWithoutGroups){ - List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>(); - arrtifacts.add(t); - Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - }; - } - - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - return Either.left(eitherGerResource.left().value()); - - } - - private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete, - Map<String, List<ArtifactDefinition>> groupToDelete) { - List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>(); - String resourceId = resource.getUniqueId(); - if (!artifactsToDelete.isEmpty()) { - for (ArtifactDefinition artifact : artifactsToDelete) { - String artifactType = artifact.getArtifactType(); - ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); - if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, - null, null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); - } - - deletedArtifacts.add(handleDelete.left().value().left().value()); - } - - } - } - if (!groupToDelete.isEmpty()) { - log.debug("try to delete group"); - List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>(); - List<GroupDefinition> groups = resource.getGroups(); - for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) { - Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny(); - if (op.isPresent()) { - groupDefinitionstoDelete.add(op.get()); - } - - } - if (!groupDefinitionstoDelete.isEmpty()) { - Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - } - return Either.left(deletedArtifacts); - } - - private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock, - boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) { - Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>(); - Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>(); - Either<Resource, ResponseFormat> resEither = Either.left(resource); - for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) { - List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts); - GroupDefinition grDef = entry.getKey(); - if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) { - for (ArtifactDefinition art : dissArtifactsInGroup) { - grDef.getArtifacts().remove(art.getUniqueId()); - grDef.getArtifactsUuid().remove(art.getArtifactUUID()); - } - } - - List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup(); - if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) - artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup); - - List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup(); - if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) - artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate); - } - - if (!artifactsToUpdateMap.isEmpty()) { - List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>(); - for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) { - List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue(); - GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey(); - - for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) { - String prevUUID = artifact.getKey().getArtifactUUID(); - String prevId = artifact.getKey().getUniqueId(); - String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey()); - Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts, - artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction); - if (updateArtifactEither.isRight()) { - log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value()); - resEither = Either.right(updateArtifactEither.right().value()); - return resEither; - } - ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value(); - if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) { - groupToUpdate.getArtifacts().remove(prevId); - groupToUpdate.getArtifactsUuid().remove(prevUUID); - groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId()); - groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); - } - Optional<ArtifactDefinition> op = updatedArtifacts.stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())).findAny(); - if (op.isPresent()) { - ArtifactDefinition artifactInfoHeatEnv = op.get(); - groupToUpdate.getArtifacts().remove(prevHeatEnvId); - groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId()); - } - - } - } - } - - for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) { - List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue(); - Set<String> arifactsUids = new HashSet<String>(); - Set<String> arifactsUuids = new HashSet<String>(); - for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try - // to - // find - // artifact - // in - // resource - boolean isCreate = true; - for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) { - if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) { - arifactsUids.add(createdArtifact.getUniqueId()); - arifactsUuids.add(createdArtifact.getArtifactUUID()); - isCreate = false; - String heatEnvId = checkAndGetHeatEnvId(createdArtifact); - if (!heatEnvId.isEmpty()) { - arifactsUids.add(heatEnvId); - Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); - if (op.isPresent()) { - this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType()); - - } - } - - break; - } - - } - if (isCreate) { // check if already created - for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) { - if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) { - arifactsUids.add(createdNewArtifact.getUniqueId()); - arifactsUuids.add(createdNewArtifact.getArtifactUUID()); - isCreate = false; - String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact); - if (!heatEnvId.isEmpty()) { - arifactsUids.add(heatEnvId); - } - break; - } - } - } - - if (isCreate) { - Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction); - if (createArtifactEither.isRight()) { - resEither = Either.right(createArtifactEither.right().value()); - return resEither; - } - ArtifactDefinition createdArtifact = createArtifactEither.left().value(); - arifactsUids.add(createdArtifact.getUniqueId()); - arifactsUuids.add(createdArtifact.getArtifactUUID()); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId(); - arifactsUids.add(heatEnvId); - } - } - - } - if (arifactsUids.size() > 0) { - List<String> artifactsToAssociate = new ArrayList<String>(); - artifactsToAssociate.addAll(arifactsUids); - GroupDefinition assotiateGroup = associateEntry.getKey(); - assotiateGroup.getArtifacts().addAll(arifactsUids); - assotiateGroup.getArtifactsUuid().addAll(arifactsUuids); - } - } - - - - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreArtifacts(false); - parametersView.setIgnoreGroups(false); - - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - resEither = Either.right(responseFormat); - return resEither; - - } - resEither = Either.left(eitherGerResource.left().value()); - return resEither; - } - - private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, - Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) { - Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>(); - for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) { - Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue(); - boolean isNeedToDeleteGroup = true; - List<ArtifactDefinition> listToDelete = null; - for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { - listToDelete = createdArtifactMap.get(maserArtifact); - for (ArtifactDefinition artToDelete : listToDelete) { - findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts); - } - if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) { - GroupDefinition group = groupListEntry.getKey(); - for (ArtifactDefinition artifactDefinition : artifactsToDelete) { - if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) { - group.getArtifacts().remove(artifactDefinition.getUniqueId()); - - } - if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) { - group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID()); - - } - } - - } - - for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { - if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) { - MergedArtifactInfo mergedGroup = new MergedArtifactInfo(); - mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact); - mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact)); - mergedgroup.put(groupListEntry.getKey(), mergedGroup); - isNeedToDeleteGroup = false; - - } - } - - } - if (isNeedToDeleteGroup) { - groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete); - } - - } - return mergedgroup; - } - - private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact, - List<ArtifactDefinition> createdDeplymentArtifacts) { - boolean isNeedToDeleteArtifact = true; - String artifactType = artifact.getArtifactType(); - ArtifactDefinition generatedFromArt = null; - if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { - Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); - if (op.isPresent()) - generatedFromArt = op.get(); - - } - - for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) { - Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue(); - for (ArtifactTemplateInfo template : artifactsNames) { - if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) { - isNeedToDeleteArtifact = false; - break; - - } else { - if (generatedFromArt != null) { - if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { - isNeedToDeleteArtifact = false; - break; - } - } - } - } - - } - if (isNeedToDeleteArtifact) { - artifactsToDelete.add(artifact); - - } - } - - private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) { - Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>(); - - for (GroupDefinition group : groups) { - Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>(); - List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); - List<String> artifactsList = group.getArtifacts(); - if (artifactsList != null && !artifactsList.isEmpty()) { - - ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList); - if (masterArtifact != null) - gupsMap.put(masterArtifact, artifacts); - groupArtifact.put(group, gupsMap); - - } - } - return groupArtifact; - } - - private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - parsedArtifactsName.add(parsedGroupTemplate); - List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); - } - } - } - - public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts, - boolean shouldLock, boolean inTransaction) { - - log.debug("parseResourceArtifactsInfoFromFile start"); - Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - log.debug("parseResourceArtifactsInfoFromFile end"); - - log.debug("createResourceArtifacts start"); - Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction); - if (respStatus.isRight()) { - return respStatus; - } - log.debug("createResourceArtifacts end"); - log.debug("getResource start"); - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("getResource end"); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - return Either.left(eitherGerResource.left().value()); - - } - - private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, - List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) { - Either<Resource, ResponseFormat> resStatus = Either.left(resource); - List<GroupDefinition> createdGroups = resource.getGroups(); - List<GroupDefinition> heatGroups = null; - if (createdGroups != null && !createdGroups.isEmpty()) { - heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - } - - List<GroupDefinition> needToAdd = new ArrayList<>(); - for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { - String groupName = groupTemplateInfo.getGroupName(); - Set<String> artifactsGroup = new HashSet<String>(); - Set<String> artifactsUUIDGroup = new HashSet<String>(); - - resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - if(groupName != null && !groupName.isEmpty()){ - Map<String, String> members = new HashMap<String, String>(); - associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members); - - List<String> artifactsList = new ArrayList<String>(artifactsGroup); - List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setName(groupName); - groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); - groupDefinition.setArtifacts(artifactsList); - groupDefinition.setArtifactsUuid(artifactsUUIDList); - - if (!members.isEmpty()) - groupDefinition.setMembers(members); - - List<GroupProperty> properties = new ArrayList<GroupProperty>(); - GroupProperty prop = new GroupProperty(); - prop.setName(Constants.IS_BASE); - prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - - List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); - createdArtifacts.addAll(createdNewArtifacts); - createdArtifacts.addAll(artifactsFromResource); - Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); - if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); - } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); - groupDefinition.convertFromGroupProperties(properties); - - needToAdd.add(groupDefinition); - } - } - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); - if (component.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - resource = component.left().value(); - - Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd); - if (addGroups.isRight()) - return Either.right(addGroups.right().value()); - - return resStatus; - } - - private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, - ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) { - Either<Resource, ResponseFormat> resStatus = Either.left(resource); - String artifactFileName = artifactTemplateInfo.getFileName(); - String artifactUid = ""; - String artifactUUID = ""; - String artifactEnvUid = ""; - boolean alreadyExist = false; - - // check if artifacts already exist - if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) { - for (ArtifactDefinition artifactFromResource : artifactsFromResource) { - if (artifactFromResource.getArtifactName().equals(artifactFileName)) { - artifactUid = artifactFromResource.getUniqueId(); - artifactUUID = artifactFromResource.getArtifactUUID(); - if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource); - break; - } - - } - - } - if (!alreadyExist) { - for (ArtifactDefinition createdArtifact : createdArtifacts) { - if (createdArtifact.getArtifactName().equals(artifactFileName)) { - artifactUid = createdArtifact.getUniqueId(); - artifactUUID = createdArtifact.getArtifactUUID(); - - if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); - break; - } - - } - } - // if not exist need to create - if (!alreadyExist) { - - Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (newArtifactEither.isRight()) { - resStatus = Either.right(newArtifactEither.right().value()); - return resStatus; - } - ArtifactDefinition newArtifact = newArtifactEither.left().value(); - artifactUid = newArtifact.getUniqueId(); - artifactUUID = newArtifact.getArtifactUUID(); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); - } - } - - artifactsGroup.add(artifactUid); - artifactsUUIDGroup.add(artifactUUID); - if (!artifactEnvUid.isEmpty()) { - artifactsGroup.add(artifactEnvUid); - } - - List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null) { - for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - return resStatus; - } - - private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource, - List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) { - - Either<Resource, ResponseFormat> resStatus = Either.left(resource); - - Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values(); - - for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) { - if (groupTemplateList != null) { - resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - - return resStatus; - - } - - private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) { - - Either<Resource, ResponseFormat> resStatus = null; - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - - try { - List<NonMetaArtifactInfo> artifactPathAndNameList = - // Stream of file paths contained in csar - csarInfo.getCsar().entrySet().stream() - // Filter in only VF artifact path location - .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // Validate and add warnings - .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)) - // Filter in Non Warnings - .filter(e -> e.isLeft()) - // Convert from Either to NonMetaArtifactInfo - .map(e -> e.left().value()) - // collect to List - .collect(Collectors.toList()); - - Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList); - if (responseFormatEither.isRight()) { - return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value())); - } - - - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null; - - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { - vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList); - } else { - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier()); - - if (findVfCsarArtifactsToHandleRes.isRight()) { - resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); - } - if (resStatus == null) { - vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); - } - } - if (resStatus == null && vfCsarArtifactsToHandle != null) { - for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) { - - Optional<ResponseFormat> optionalCreateInDBError = - // Stream of artifacts to be created - currArtifactOperationPair.getValue().stream() - // create each artifact - .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock, - inTransaction)) - // filter in only error - .filter(e -> e.isRight()). - // Convert the error from either to ResponseFormat - map(e -> e.right().value()). - // Check if an error occurred - findAny(); - // Error found on artifact Creation - if (optionalCreateInDBError.isPresent()) { - resStatus = Either.right(optionalCreateInDBError.get()); - break; - } - } - } - if (resStatus == null) { - resStatus = Either.left(resource); - } - } catch (Exception e) { - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); - } finally { - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - return resStatus; - } - - private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) { - Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); - for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { - if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { - return Either.right(nonMetaArtifactInfo.getArtifactName()); - } - } - return Either.left(true); - } - - - private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) { - - List<ArtifactDefinition> existingArtifacts = new ArrayList<>(); - // collect all Deployment and Informational artifacts of VF - if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); - } - if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getArtifacts().values()); - } - existingArtifacts = existingArtifacts.stream() - // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta - .filter(this::isNonMetaArtifact).collect(Collectors.toList()); - - List<String> artifactsToIgnore = new ArrayList<>(); - // collect IDs of Artifacts of VF which belongs to any group - if (resource.getGroups() != null) { - resource.getGroups().stream().forEach(g -> { - if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) - artifactsToIgnore.addAll(g.getArtifacts()); - }); - } - existingArtifacts = existingArtifacts.stream() - // filter artifacts which belongs to any group - .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList()); - return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); - } - - private boolean isNonMetaArtifact(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { - result = false; - } - return result; - } - - private boolean isValidArtifactType(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { - result = false; - } - return result; - } - - private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts, - int labelCounter, boolean shouldLock, boolean inTransaction) { - Either<Resource, ResponseFormat> resStatus = Either.left(resource); - List<GroupDefinition> createdGroups = resource.getGroups(); - List<GroupDefinition> heatGroups = null; - if (createdGroups != null && !createdGroups.isEmpty()) { - - // List<IArtifactInfo> collect = resources.stream().flatMap( e -> - // e.getArtifacts().stream()).filter(p -> - // relevantArtifactTypes.contains(p.getArtifactType() - // )).collect(Collectors.toList()); - // List<GroupDefinition> heatGroups = createdGroups.stream().filter( - // e -> e.getProperties().stream().filter(p -> - // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList()); - heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - ; - } - List<GroupDefinition> needToCreate = new ArrayList<>(); - for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { - String groupName = groupTemplateInfo.getGroupName(); - Set<String> artifactsGroup = new HashSet<String>(); - Set<String> artifactsUUIDGroup = new HashSet<String>(); - - log.debug("createDeploymentArtifactsFromCsar start"); - resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); - log.debug("createDeploymentArtifactsFromCsar end"); - if (resStatus.isRight()) - return resStatus; - if(groupName != null && !groupName.isEmpty()){ - Map<String, String> members = new HashMap<String, String>(); - associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); - - List<String> artifactsList = new ArrayList<String>(artifactsGroup); - List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setName(groupName); - groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); - groupDefinition.setArtifacts(artifactsList); - groupDefinition.setArtifactsUuid(artifactsUUIDList); - - if (!members.isEmpty()) - groupDefinition.setMembers(members); - List<GroupProperty> properties = new ArrayList<GroupProperty>(); - GroupProperty prop = new GroupProperty(); - prop.setName(Constants.IS_BASE); - prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); - if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); - } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); - groupDefinition.convertFromGroupProperties(properties); - log.debug("createGroup start"); - - needToCreate.add(groupDefinition); - } - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreGroups(false); - - componentParametersView.setIgnoreComponentInstances(false); - - Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); - if (component.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); - } - - return resStatus; - } - - public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) { - Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties(); - vfModuleProperties.entrySet().forEach(p -> { - GroupProperty prop = new GroupProperty(); - prop.setName(p.getKey()); - if (isBase) { - prop.setValue(p.getValue().getForBaseModule()); - prop.setDefaultValue(p.getValue().getForBaseModule()); - } else { - prop.setValue(p.getValue().getForNonBaseModule()); - prop.setDefaultValue(p.getValue().getForNonBaseModule()); - } - properties.add(prop); - - }); - GroupProperty proplabel = new GroupProperty(); - proplabel.setName("vf_module_label"); - - Matcher matcher = pattern.matcher(moduleName); - - if (matcher.find()) { - proplabel.setValue(matcher.group(1)); - proplabel.setDefaultValue(matcher.group(1)); - } else { - proplabel.setValue(moduleName); - proplabel.setDefaultValue(moduleName); - } - properties.add(proplabel); - - GroupProperty propvolume = new GroupProperty(); - propvolume.setName("volume_group"); - boolean isVolume = false; - for (String artifactId : artifactsInGroup) { - ArtifactDefinition artifactDef = null; - artifactDef = findArtifactInList(deploymentArtifacts, artifactId); - if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { - isVolume = true; - break; - } - } - propvolume.setValue(String.valueOf(isVolume)); - propvolume.setDefaultValue(String.valueOf(isVolume)); - properties.add(propvolume); - mergeWithGroupTypeProperties(properties, groupType.getProperties()); - return properties; - } - - private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) { - - Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - for (PropertyDefinition groupTypeProperty : groupTypeProperties) { - if (!propertiesMap.containsKey(groupTypeProperty.getName())) { - properties.add(new GroupProperty(groupTypeProperty)); - } - } - } - - private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) { - for (ArtifactDefinition artifact : createdArtifacts) { - if (artifact.getUniqueId().equals(artifactId)) { - return artifact; - } - } - return null; - } - - private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) { - if (heatGroups != null && !heatGroups.isEmpty()) { - for (GroupDefinition heatGroup : heatGroups) { - List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties(); - if (grpoupProps != null) { - Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny(); - if (op.isPresent()) { - GroupProperty prop = op.get(); - String heatFileNAme = prop.getValue(); - if (null == heatFileNAme || heatFileNAme.isEmpty()) - continue; - List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>(); - for (String artifactId : artifactsGroup) { - Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); - if (opArt.isPresent()) { - artifacts.add(opArt.get()); - } - if (artifactsFromResource != null) { - opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); - if (opArt.isPresent()) { - artifacts.add(opArt.get()); - } - } - } - Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); - if (resOp.isPresent()) { - members.putAll(heatGroup.getMembers()); - } - } - } - } - - } - } - - private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, - ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { - Either<Resource, ResponseFormat> resStatus = Either.left(resource); - String artifactFileName = artifactTemplateInfo.getFileName(); - String artifactUid = ""; - String artifactEnvUid = ""; - String artifactUUID = ""; - boolean alreadyExist = false; - - // check if artifacts already exist - for (ArtifactDefinition createdArtifact : createdArtifacts) { - if (createdArtifact.getArtifactName().equals(artifactFileName)) { - artifactUid = createdArtifact.getUniqueId(); - artifactUUID = createdArtifact.getArtifactUUID(); - if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); - break; - } - } - // if not exist need to create - if (!alreadyExist) { - - Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (newArtifactEither.isRight()) { - resStatus = Either.right(newArtifactEither.right().value()); - return resStatus; - } - ArtifactDefinition newArtifact = newArtifactEither.left().value(); - artifactUid = newArtifact.getUniqueId(); - artifactUUID = newArtifact.getArtifactUUID(); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); - } - } - - artifactsGroup.add(artifactUid); - artifactsUUIDGroup.add(artifactUUID); - if (!artifactEnvUid.isEmpty()) { - artifactsGroup.add(artifactEnvUid); - } - - List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null) { - for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - return resStatus; - } - - private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { - String artifactEnvUid = ""; - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX; - } - return artifactEnvUid; - } - - private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, - List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { - final String artifactFileName = artifactTemplateInfo.getFileName(); - Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils); - if (artifactContententStatus.isRight()) { - return Either.right(artifactContententStatus.right().value()); - } - labelCounter += createdArtifacts.size(); - - Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter); - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), - shoudLock, inTransaction); - - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); - if (currentInfo.getHeatParameters() != null) { - - Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false); - if (updateEnvEither.isRight()) { - log.debug("failed to update parameters to artifact {}", artifactFileName); - return Either.right(updateEnvEither.right().value()); - - } - currentInfo = updateEnvEither.left().value(); - - } - - createdArtifacts.add(currentInfo); - - return Either.left(currentInfo); - - } - - private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo, - List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) { - - Either<ArtifactDefinition, ResponseFormat> resStatus = null; - String artifactFileName = artifactTemplateInfo.getFileName(); - - // check if artifacts already exist - for (ArtifactDefinition updatedArtifact : updatedArtifacts) { - if (updatedArtifact.getArtifactName().equals(artifactFileName)) { - if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType())); - return resStatus; - } - resStatus = Either.left(updatedArtifact); - return resStatus; - } - - } - - Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); - if (artifactContententStatus.isRight()) { - resStatus = Either.right(artifactContententStatus.right().value()); - return resStatus; - } - - Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), - oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts); - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), - shouldLock, inTransaction); - - if (uploadArtifactToService.isRight()) { - resStatus = Either.right(uploadArtifactToService.right().value()); - return resStatus; - } - ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); - updatedArtifacts.add(currentInfo); - - Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true); - if (updateEnvEither.isRight()) { - log.debug("failed to update parameters to artifact {}", artifactFileName); - resStatus = Either.right(updateEnvEither.right().value()); - return resStatus; - } - // TODO evg update env time ( must be separate US for this!!!!) - - updatedArtifacts.add(updateEnvEither.left().value()); - resStatus = Either.left(currentInfo); - - return resStatus; - - } - - private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { - Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo); - if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { - - Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), - componentsUtils); - if (artifactparamsStatus.isRight()) { - resStatus = Either.right(artifactparamsStatus.right().value()); - return resStatus; - } - Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false); - - if (propsStatus.isLeft()) { - List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value(); - List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters(); - // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { - - String paramName; - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue == null) - updatedParamValue = heatEnvParam.getDefaultValue(); - HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); - if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); - resStatus = Either.right(responseFormat); - return resStatus; - } - currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); - // newHeatEnvParams.add(currHeatParam); - break; - } - } - } - currentInfo.setListHeatParameters(currentHeatEnvParams); - Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null); - if (updateArifactOnResource.isRight()) { - log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); - } - resStatus = Either.left(updateArifactOnResource.left().value()); - } - } - } - if (isUpdateEnv) { - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreArtifacts(false); - parametersView.setIgnoreGroups(false); - - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - resStatus = Either.right(responseFormat); - return resStatus; - - } - resource = eitherGerResource.left().value(); - Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts(); - Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny(); - if (op.isPresent()) { - ArtifactDefinition artifactInfoHeatEnv = op.get(); - Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null); - if (updateArifactOnResource.isRight()) { - log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); - } - resStatus = Either.left(updateArifactOnResource.left().value()); - } - } - return resStatus; - } - - private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) { - // extract heat parameters - String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content); - Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType); - if (heatParameters.isRight()) { - log.debug("File {} is not in expected key-value form in csar ", fileName); - BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName)); - - } - return Either.left(heatParameters.left().value()); - - } - - private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) { - - Map<String, Object> json = new HashMap<String, Object>(); - String artifactName = artifactTemplateInfo.getFileName(); - - json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName()); - json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType()); - json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar"); - - // DE250204: There is no need to check if base64 encoding. - - // String encodedPayload = new String(artifactContentent); - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - String encodedPayload = Base64.encodeBase64String(artifactContentent); - // } - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - String displayName = artifactName; - if (artifactName.lastIndexOf(".") > 0) - displayName = artifactName.substring(0, artifactName.lastIndexOf(".")); - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>() - : requiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - return json; - } - - private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent, - List<ArtifactTemplateInfo> updatedRequiredArtifacts) { - - Map<String, Object> json = new HashMap<String, Object>(); - if (artifactId != null && !artifactId.isEmpty()) - json.put(Constants.ARTIFACT_ID, artifactId); - - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_TYPE, artifactType); - json.put(Constants.ARTIFACT_DESCRIPTION, description); - - String encodedPayload = new String(artifactContentent); - - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - log.debug("payload is encoded. perform decode"); - encodedPayload = Base64.encodeBase64String(artifactContentent); - // } - - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); - json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() - : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - return json; - } - - @SuppressWarnings({ "unchecked", "static-access" }) - private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) { - - try { - JsonObject jsonElement = new JsonObject(); - jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass()); - - JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE); - if (importStructureElement == null || importStructureElement.isJsonNull()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>(); - artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class); - if (artifactTemplateMap.isEmpty()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - Set<String> artifactsTypeKeys = artifactTemplateMap.keySet(); - Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>(); - List<ArtifactTemplateInfo> allGroups = new ArrayList<>(); - for (String artifactsTypeKey : artifactsTypeKeys) { - - List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey); - Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o); - if (artifactTemplateInfoListPairStatus.isRight()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(artifactTemplateInfoListPairStatus.right().value()); - } - List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value(); - if (artifactTemplateInfoList == null) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - - } - if(!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) - allGroups.addAll(artifactTemplateInfoList); - artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList); - } - int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups()); - Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter); - if (validateGroupNamesRes.isRight()) { - return Either.right(validateGroupNamesRes.right().value()); - } - return Either.left(artifactsMap); - } catch (Exception e) { - log.debug("Artifact file is not in expected format, fileName {}", artifactFileName); - log.debug("failed with exception.", e); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - } - - private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) { - List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>(); - for (Map<String, Object> o : jsonObject) { - Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null); - if (artifacttemplateInfoStatus.isRight()) { - return Either.right(artifacttemplateInfoStatus.right().value()); - } - - ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value(); - if (artifacttemplateInfo != null) { - artifactTemplateInfoList.add(artifacttemplateInfo); - } - - } - return Either.left(artifactTemplateInfoList); - } - - private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { - log.debug("createResourceInstancesRelations try to create relations "); - List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); - if (uploadResInstancesMap == null) { - log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - if (componentInstancesList == null || componentInstancesList.isEmpty()) { - log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - log.debug("Before validateAndUpdatePropertyValue"); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName)); - - } - - Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>(); - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>(); - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>(); - Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>(); - Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>(); - Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>(); - Map<String, Resource> originCompMap = new HashMap<>(); - List<RequirementCapabilityRelDef> relations = new ArrayList<>(); - - Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>(); - - for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { - log.trace("Processing entry: {}", entry); - UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); - ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - log.trace("Processing component instance: {}", compInstance); - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - Resource originResource; - if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { - Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid()); - if (getOriginResourceRes.isRight()) { - log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); - return Either.right(responseFormat); - } - originResource = getOriginResourceRes.left().value(); - originCompMap.put(originResource.getUniqueId(), originResource); - } else { - originResource = originCompMap.get(currentCompInstance.getComponentUid()); - } - if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) - instRequirements.put(currentCompInstance, originResource.getRequirements()); - if (MapUtils.isNotEmpty(originResource.getCapabilities())) { - Map<String, List<CapabilityDefinition>> originCapabilities ; - if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { - originCapabilities = new HashMap<>(); - originResource.getCapabilities().entrySet().stream().forEach(e ->{ - List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList()); - originCapabilities.put(e.getKey(), list); - }); - Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>(); - for(List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()){ - for(UploadCapInfo capability :capabilities){ - if(CollectionUtils.isNotEmpty(capability.getProperties())){ - newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p))); - } - } - } - for (List<CapabilityDefinition> capabilities : originCapabilities.values()) { - List<CapabilityDefinition> filteredCapabilities = capabilities.stream().filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList()); - for(CapabilityDefinition cap : filteredCapabilities){ - Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(),newPropertiesMap.get(cap.getName()), allDataTypes.left().value()); - if(updateRes.isRight()){ - log.debug("Failed to update capability properties of capability {} . Status is {}. ", cap.getName(), updateRes.right().value()); - return Either.right(updateRes.right().value()); - } - } - } - } - else{ - originCapabilities = originResource.getCapabilities(); - } - instCapabilties.put(currentCompInstance, originCapabilities); - } - if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) - instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); - if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) - instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); - if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) - instAttributes.put(resourceInstanceId, originResource.getAttributes()); - if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { - ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value()); - if (addPropertiesValueToRiRes.getStatus() != 200) { - return Either.right(addPropertiesValueToRiRes); - } - } else { - ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value()); - if (addInputValueToRiRes.getStatus() != 200) { - return Either.right(addInputValueToRiRes); - } - } - } - - Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); - if (addPropToInst.isRight()) { - log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName); - return Either.right(responseFormat); - } - if (instInputs != null && !instInputs.isEmpty()) { - Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); - if (addInputToInst.isRight()) { - log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName); - return Either.right(responseFormat); - } - } - StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreComponentInstancesProperties(false); - parametersView.setIgnoreCapabilities(false); - parametersView.setIgnoreRequirements(false); - - Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - - return Either.right(responseFormat); - - } - - resource = eitherGetResource.left().value(); - - for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { - UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); - ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); - if (addRelationToRiRes.getStatus() != 200) { - return Either.right(addRelationToRiRes); - } - } - - addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - if(resource.getResourceType() == ResourceTypeEnum.CVFC){ - eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(), uploadResInstancesMap); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - } - - log.debug("************* in create relations, getResource start"); - eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(eitherGetResource.left().value()); - } - - private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) { - for(ComponentInstanceProperty property : properties){ - Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property ,newProperties.get(property.getName()), allDataTypes); - if(updateRes.isRight()){ - log.debug("Failed to update capability property {} . Status is {}. ", property.getName(), updateRes.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value()))); - } - } - return Either.left(true); - } - - private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) { - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - property.setValue(value); - return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes); - } - - private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { - Either<Resource, StorageOperationStatus> updateRes = null; - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>(); - Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>(); - StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId()); - if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){ - log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status); - updateRes = Either.right(status); - } - if(updateRes == null){ - fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements); - status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status); - updateRes = Either.right(status); - } - } - if(updateRes == null){ - updateRes = Either.left(resource); - } - return updateRes; - } - - - private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, - Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) { - - componentInstances.stream().forEach( i -> { - fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); - fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); - }); - } - - private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) { - Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>(); - Set<String> updatedReqNames = new HashSet<>(); - if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){ - for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) { - updatedRequirements.put(requirements.getKey(), requirements.getValue().stream() - .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) - .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;}) - .collect(Collectors.toList())); - } - } - if(MapUtils.isNotEmpty(updatedRequirements)){ - updatedInstRequirements.put(instance, updatedRequirements); - } - } - - private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) { - Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>(); - Set<String> updatedCapNames = new HashSet<>(); - if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){ - for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) { - updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream() - .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) - .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;}) - .collect(Collectors.toList())); - } - } - if(MapUtils.isNotEmpty(updatedCapabilities)){ - updatedInstCapabilties.put(instance, updatedCapabilities); - } - } - - private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) { - List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); - - UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue; - - ComponentInstance currentCompInstance = null; - - for (ComponentInstance compInstance : componentInstancesList) { - - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - - Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements(); - - if (regMap != null) { - Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator(); - - while (nodesRegValue.hasNext()) { - Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next(); - - List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue(); - for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { - log.debug("Going to create relation {}", uploadRegInfo.getName()); - String regName = uploadRegInfo.getName(); - RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); - regCapRelDef.setFromNode(resourceInstanceId); - log.debug("try to find available requirement {} ", regName); - Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName()); - if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value()); - return eitherReqStatus.right().value(); - } - - RequirementDefinition validReq = eitherReqStatus.left().value(); - List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships(); - if (reqAndRelationshipPairList == null) - reqAndRelationshipPairList = new ArrayList<>(); - RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); - reqAndRelationshipPair.setRequirement(regName); - reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); - reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(validReq.getCapability()); - reqAndRelationshipPair.setRelationships(relationship); - - ComponentInstance currentCapCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(uploadRegInfo.getNode())) { - currentCapCompInstance = compInstance; - break; - } - } - - if (currentCapCompInstance == null) { - log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); - log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); - if (aviableCapForRel == null) { - log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(), - ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); - reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); - reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(reqAndRelationshipPair); - reqAndRelationshipPairList.add(capReqRel); - regCapRelDef.setRelationships(reqAndRelationshipPairList); - relations.add(regCapRelDef); - } - } - } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); - return responseFormat; - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, - Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) { - Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); - if (propMap != null && propMap.size() > 0) { - Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>(); - - List<InputDefinition> listFromMap = originResource.getInputs(); - if (listFromMap == null || listFromMap.isEmpty()) { - log.debug("failed to find properties "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - return responseFormat; - } - for (InputDefinition prop : listFromMap) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - List<ComponentInstanceInput> instPropList = new ArrayList<>(); - for (List<UploadPropInfo> propertyList : propMap.values()) { - - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - return responseFormat; - } - InputDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceInput property = null; - - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - String innerType = null; - property = new ComponentInstanceInput(curPropertyDef, value, null); - - Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); - } - - // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++); - // property.setUniqueId(uniqueId); - property.setValue(validatevalueEiter.left().value()); - - if (getInputs != null && !getInputs.isEmpty()) { - List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List<InputDefinition> inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId()); - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - - Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - } - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - // add rest of properties - if (!currPropertiesMap.isEmpty()) { - for (InputDefinition value : currPropertiesMap.values()) { - instPropList.add(new ComponentInstanceInput(value)); - } - } - instInputs.put(currentCompInstance.getUniqueId(), instPropList); - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, - Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) { - - Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); - Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>(); - - List<PropertyDefinition> listFromMap = originResource.getProperties(); - if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { - log.debug("failed to find properties "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - return responseFormat; - } - if(listFromMap == null || listFromMap.isEmpty()){ - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - for (PropertyDefinition prop : listFromMap) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - List<ComponentInstanceProperty> instPropList = new ArrayList<>(); - if (propMap != null && propMap.size() > 0) { - for (List<UploadPropInfo> propertyList : propMap.values()) { - - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - return responseFormat; - } - PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceProperty property = null; - - String value = null; - List<GetInputValueDataDefinition> getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - String innerType = null; - property = new ComponentInstanceProperty(curPropertyDef, value, null); - - Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); - } - - property.setValue(validatevalueEiter.left().value()); - - if (getInputs != null && !getInputs.isEmpty()) { - List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List<InputDefinition> inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId()); - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - - Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - - } - - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - } - // add rest of properties - if (!currPropertiesMap.isEmpty()) { - for (PropertyDefinition value : currPropertiesMap.values()) { - instPropList.add(new ComponentInstanceProperty(value)); - } - } - instProperties.put(currentCompInstance.getUniqueId(), instPropList); - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - // US740820 Relate RIs according to capability name - private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get - // by - // capability - // type - return findAviableCapability(validReq, currentCapCompInstance); - } - return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); - } - - private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - CapabilityDefinition cap = null; - Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); - if (!capMap.containsKey(validReq.getCapability())) { - return null; - } - Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); - if (!capByName.isPresent()) { - return null; - } - cap = capByName.get(); - - if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = cap.getLeftOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - - } - - } - return cap; - } - - private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) { - CapabilityDefinition aviableCapForRel = null; - Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); - if (capMap.containsKey(validReq.getCapability())) { - List<CapabilityDefinition> capList = capMap.get(validReq.getCapability()); - - for (CapabilityDefinition cap : capList) { - if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = cap.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = cap.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - aviableCapForRel = cap; - break; - } else { - continue; - } - } else { - aviableCapForRel = cap; - break; - } - } - } - return aviableCapForRel; - } - - private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) { - Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements(); - List<RequirementDefinition> list = comInstRegDefMap.get(capName); - RequirementDefinition validRegDef = null; - if (list == null) { - for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) { - for (RequirementDefinition reqDef : entry.getValue()) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - - } - } - if (validRegDef != null) { - break; - } - } - } else { - for (RequirementDefinition reqDef : list) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - } - } - } - if (validRegDef == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - return Either.left(validRegDef); - } - - @SuppressWarnings("unchecked") - public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) { - - Map<String, Object> mappedToscaTemplate; - if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){ - mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); - } - else { - try { - //DE154502 Fail if duplicate key found in file - mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml); - - } catch(ParserException e) { - log.error("Failed to load yaml file {}", yamlFileName, e); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage()); - return Either.right(responseFormat); - } - } - Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - if (toscaElementEither.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - return Either.right(responseFormat); - } - - Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource); - if (createInputsEither.isRight()) { - ResponseFormat responseFormat = createInputsEither.right().value(); - return Either.right(responseFormat); - } - - Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames); - if (uploadResInstancesEither.isRight()) { - ResponseFormat responseFormat = uploadResInstancesEither.right().value(); - return Either.right(responseFormat); - } - - Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource); - if (createGroupsFromYaml.isRight()) { - ResponseFormat responseFormat = createGroupsFromYaml.right().value(); - return Either.right(responseFormat); - } - - ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo(); - parsedToscaYamlInfo.setInputs(createInputsEither.left().value()); - parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value()); - parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value()); - - return Either.left(parsedToscaYamlInfo); - } - - private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock, - Map<String, Resource> nodeNamespaceMap) { - - Either<Resource, ResponseFormat> eitherResource = null; - log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); - if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - - return Either.right(responseFormat); - - } - Map<String, Resource> existingnodeTypeMap = new HashMap<>(); - if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) { - nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue())); - } - - Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator(); - Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>(); - while (nodesInfoValue.hasNext()) { - log.debug("*************Going to create resource instances {}", yamlName); - Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next(); - UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); - - // updating type if the type is node type name - we need to take the - // updated name - log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); - } - - eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap); - if (eitherResource.isRight()) { - return eitherResource; - } - Resource refResource = eitherResource.left().value(); - - ComponentInstance componentInstance = new ComponentInstance(); - - componentInstance.setComponentUid(refResource.getUniqueId()); - - ComponentTypeEnum containerComponentType = resource.getComponentType(); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - - if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils.isNotEmpty(refResource.getCapabilities())) { - setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - if (getValidComponentInstanceCapabilitiesRes.isRight()) { - return Either.right(getValidComponentInstanceCapabilitiesRes.right().value()); - } else { - componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value()); - } - } - if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { - log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); - componentInstance.setName(uploadComponentInstanceInfo.getName()); - componentInstance.setIcon(origResource.getIcon()); - - resourcesInstancesMap.put(componentInstance, origResource); - - } - if (MapUtils.isNotEmpty(resourcesInstancesMap)) { - - StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false); - if (status != null && status != StorageOperationStatus.OK) { - log.debug("Failed to add component instances to container component {}", resource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)); - eitherResource = Either.right(responseFormat); - return eitherResource; - } - - } - - log.debug("*************Going to get resource {}", resource.getUniqueId()); - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreInputs(false); // inputs are read when creating - // property values on instances - Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - log.debug("*************finished to get resource {}", resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - - if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) { - - log.debug("Error when create resource inctanse from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - return Either.right(responseFormat); - - } - - return Either.left(eitherGerResource.left().value()); - } - - private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) { - for(Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()){ - if(originCapabilities.containsKey(currEntry.getKey())){ - currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); - } - } - for(Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()){ - capabilities.getValue().stream().forEach(cap -> {if(uploadedCapabilities.containsKey(cap.getName())){uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {c.setName(cap.getName());c.setType(cap.getType());});};}); - } - - } - - private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) { - log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - Resource refResource = null; - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); - } else { - Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); - if (findResourceEither.isRight()) { - log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); - return Either.right(responseFormat); - } - refResource = findResourceEither.left().value(); - nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); - } - String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); - if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState); - return Either.right(responseFormat); - } - - if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { - log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - return Either.left(refResource); - } - - private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) { - Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>(); - Map<String, Object> substitutionMappings = null; - Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances); - Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES); - Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS); - if (eitherSubstitutionMappings.isLeft()) { - substitutionMappings = eitherSubstitutionMappings.left().value(); - } - if (eitherNodesTemlates.isLeft()) { - Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value(); - - Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry<String, Object> nodeNameValue = nodesNameValue.next(); - Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames); - if (eitherNode.isRight()) { - log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName()); - return Either.right(eitherNode.right().value()); - } else { - UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value(); - moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo); - } - - } - - } - if (moduleComponentInstances.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); - return Either.right(responseFormat); - } - - return result; - } - - @SuppressWarnings("unchecked") - private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) { - - UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo(); - Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo); - nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey()); - try { - if (nodeTemplateJsonEntry.getValue() instanceof String) { - String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue(); - nodeTemplateInfo.setType(nodeTemplateJsonString); - } else if (nodeTemplateJsonEntry.getValue() instanceof Map) { - Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue(); - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) { - toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType); - } - nodeTemplateInfo.setType(toscaResourceType); - } - - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { - Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - nodeTemplateInfo.setRequirements(regResponse.left().value()); - } - } - - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { - Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap); - if (eitherCapRes.isRight()) - return Either.right(eitherCapRes.right().value()); - if (eitherCapRes.left().value().size() > 0) { - nodeTemplateInfo.setCapabilities(eitherCapRes.left().value()); - } - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - nodeTemplateInfo.setProperties(regResponse.left().value()); - } - } - if (substitutionMappings != null) { - if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { - Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); - if (getCapNamesToUpdateRes.isRight()) - return Either.right(getCapNamesToUpdateRes.right().value()); - if (getCapNamesToUpdateRes.left().value().size() > 0) { - nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value()); - } - } - if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { - Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); - if (getReqNamesToUpdateRes.isRight()) - return Either.right(getReqNamesToUpdateRes.right().value()); - if (getReqNamesToUpdateRes.left().value().size() > 0) { - nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value()); - } - } - } - } else { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); - log.debug("error when creating capability, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) { - Either<Map<String, String>, ResponseFormat> response; - try { - Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey())); - response = Either.left(namesToUpdate); - } catch (Exception e) { - log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName()); - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return response; - } - - @SuppressWarnings("unchecked") - private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) { - Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>(); - Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp); - Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES); - if (toscaProperties.isLeft()) { - Map<String, Object> jsonProperties = toscaProperties.left().value(); - for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) { - // Property - String propName = jsonPropObj.getKey(); - Object propValue = jsonPropObj.getValue(); - - if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - if (valueContainsPattern(TOKEN_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - if (valueContainsPattern(CONCAT_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - UploadPropInfo propertyDef = new UploadPropInfo(); - propertyDef.setValue(propValue); - propertyDef.setName(propName); - if (propValue instanceof Map) { - if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString()); - } - - if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()) - || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef); - } - - if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString()); - } - if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) { - propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())); - } - if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) { - propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString())); - } else { - propertyDef.setValue(propValue); - } - } else if (propValue instanceof List) { - List<Object> propValueList = (List<Object>) propValue; - - createInputPropList(propertyDef, propValueList); - propertyDef.setValue(propValue); - } - - if (moduleProp.containsKey(propName)) { - moduleProp.get(propName).add(propertyDef); - } else { - List<UploadPropInfo> list = new ArrayList<UploadPropInfo>(); - list.add(propertyDef); - moduleProp.put(propName, list); - } - } - } - return response; - } - - @SuppressWarnings("unchecked") - private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) { - for (Object objValue : propValueList) { - - if (objValue instanceof Map) { - Map<String, Object> objMap = (Map<String, Object>) objValue; - if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) - createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef); - else { - Set<String> keys = objMap.keySet(); - for (String key : keys) { - Object value = objMap.get(key); - if (value instanceof Map) { - createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef); - - } else if (value instanceof List) { - List<Object> propSubValueList = (List<Object>) value; - - createInputPropList(propertyDef, propSubValueList); - } - - } - } - - } else if (objValue instanceof List) { - List<Object> propSubValueList = (List<Object>) objValue; - - createInputPropList(propertyDef, propSubValueList); - - } - - } - } - - @SuppressWarnings("unchecked") - private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) { - - if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); - List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input(); - if (getInputs == null) { - getInputs = new ArrayList<GetInputValueDataDefinition>(); - } - if (getInput instanceof String) { - - getInputInfo.setInputName((String) getInput); - getInputInfo.setPropName(propName); - - } else if (getInput instanceof List) { - List<Object> getInputList = (List<Object>) getInput; - getInputInfo.setPropName(propName); - getInputInfo.setInputName((String) getInputList.get(0)); - if (getInputList.size() > 1) { - Object indexObj = getInputList.get(1); - if (indexObj instanceof Integer) { - getInputInfo.setIndexValue((Integer) indexObj); - } else if (indexObj instanceof Float) { - int index = ((Float) indexObj).intValue(); - getInputInfo.setIndexValue(index); - } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); - getInputInfoIndex.setInputName((String) index); - getInputInfoIndex.setPropName(propName); - getInputInfo.setGetInputIndex(getInputInfoIndex); - } - getInputInfo.setList(true); - } - - } - getInputs.add(getInputInfo); - propertyDef.setGet_input(getInputs); - propertyDef.setValue(propValue); - } else { - Set<String> keys = propValue.keySet(); - for (String key : keys) { - Object value = propValue.get(key); - if (value instanceof Map) { - createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef); - - } else if (value instanceof List) { - List<Object> valueList = (List<Object>) value; - for (Object o : valueList) { - if (o instanceof Map) { - createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef); - - } - } - - } - - } - - } - } - - /* - * private boolean valueContainsStrReplace(Object propValue) { - * - * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher = - * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); } - * - * return result; } - * - * private boolean valueContainsToken(Object propValue) { - * - * log.debug("valueContainsToken value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsToken value is {}", propValue.getClass()); Matcher matcher = TOKEN_PATTERN.matcher(propValue.toString()); result = - * matcher.find(); } - * - * return result; } - */ - - private boolean valueContainsPattern(Pattern pattern, Object propValue) { - - log.debug("valueContainsToken value is {}", propValue); - boolean result = false; - if (propValue != null) { - log.trace("valueContainspattern value is {}", propValue.getClass()); - Matcher matcher = pattern.matcher(propValue.toString()); - result = matcher.find(); - } - - return result; - - } - @SuppressWarnings("unchecked") - private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) { - Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>(); - Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements); - Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); - - if (requirementsListRes.isLeft()) { - for (Object jsonReqObj : requirementsListRes.left().value()) { - String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next(); - Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName); - Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } else { - Either<Map<String,Object>, ResultStatusEnum> requirementsMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); - if (requirementsMapRes.isLeft()) { - for (Map.Entry<String, Object> entry: requirementsMapRes.left().value().entrySet()) { - String reqName = entry.getKey(); - Object reqJson = entry.getValue(); - Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } - } - return response; - } - - private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) { - - Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson); - if (eitherRequirement.isRight()) { - log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo); - return Either.right(eitherRequirement.right().value()); - } else { - UploadReqInfo requirementDef = eitherRequirement.left().value(); - requirementDef.setName(requirementName); - if (moduleRequirements.containsKey(requirementName)) { - moduleRequirements.get(requirementName).add(requirementDef); - } else { - List<UploadReqInfo> list = new ArrayList<UploadReqInfo>(); - list.add(requirementDef); - moduleRequirements.put(requirementName, list); - } - } - return Either.left(eitherRequirement.left().value()); - } - - @SuppressWarnings("unchecked") - private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) { - Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>(); - Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap); - Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); - if (capabilitiesListRes.isLeft()) { - for (Object jsonCapObj : capabilitiesListRes.left().value()) { - String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next(); - Object capJson = ((Map<String, Object>) jsonCapObj).get(key); - Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, key); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } else { - Either<Map<String,Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); - if (capabilitiesMapRes.isLeft()) { - for (Map.Entry<String, Object> entry: capabilitiesMapRes.left().value().entrySet()) { - String capName = entry.getKey(); - Object capJson = entry.getValue(); - Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, capName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } - } - return response; - } - - private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) { - - Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson); - if (eitherCap.isRight()) { - log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo); - return Either.right(eitherCap.right().value()); - } else { - UploadCapInfo capabilityDef = eitherCap.left().value(); - capabilityDef.setKey(key); - if (moduleCap.containsKey(key)) { - moduleCap.get(key).add(capabilityDef); - } else { - List<UploadCapInfo> list = new ArrayList<UploadCapInfo>(); - list.add(capabilityDef); - moduleCap.put(key, list); - } - } - return Either.left( eitherCap.left().value()); - } - - @SuppressWarnings("unchecked") - private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) { - UploadCapInfo capTemplateInfo = new UploadCapInfo(); - Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo); - - if (capObject instanceof String) { - String nodeTemplateJsonString = (String) capObject; - capTemplateInfo.setNode(nodeTemplateJsonString); - } else if (capObject instanceof Map) { - Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject; - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES); - if (validSourceTypesRes.isLeft()) { - capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList())); - } - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (!regResponse.left().value().isEmpty()) { - List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>(); - regResponse.left().value().values().forEach(list -> properties.addAll(list)); - if (!properties.isEmpty()) - capTemplateInfo.setProperties(properties); - } - } - } - return result; - } - - @SuppressWarnings("unchecked") - private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) { - - UploadReqInfo regTemplateInfo = new UploadReqInfo(); - Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo); - - if (regObject instanceof String) { - String nodeTemplateJsonString = (String) regObject; - regTemplateInfo.setNode(nodeTemplateJsonString); - } else if (regObject instanceof Map) { - Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject; - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - // US740820 Relate RIs according to capability name - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { - regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); - } - } - return result; - } - - public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) { - - Either<Resource, ResponseFormat> result = null; - try { - if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){ - result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - if(result.isRight()){ - return result; - } - resource = result.left().value(); - } - if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock); - result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value()); - return result; - } - return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); - } catch (Exception e) { - log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - - private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock); - if (result.isLeft()) { - result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock); - } - if (result.isLeft()) { - result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock); - } - return result; - } - - private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - } - - /* - * /** - * - * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead - */ - /* - * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return - * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); } - */ - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, String nodeName, boolean isNested) { - - // check if resource already exist - Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName()); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null; - - // create - if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - - Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName()); - if (csarInfo!= null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ - latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight()); - // update - if (latestByToscaName.isLeft()) { - log.debug("validate derived before update"); - Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(latestByToscaName.left().value(), resource, ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion())); - if (eitherValidation.isRight()) { - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } else { - result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, isNormative, needLock, isNested); - } - } - } - if (result == null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } else if (result == null){ - StorageOperationStatus status = latestByName.right().value(); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - log.debug("resource already exist {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - } - - } - - // update - else if (latestByName.isLeft()) { - result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, isNested); - } - - // error - else { - StorageOperationStatus status = latestByName.right().value(); - log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - } - return result; - - } - - private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { - log.debug("resource with name {} does not exist. create new resource", resource.getName()); - Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); - if (response.isRight()) { - return Either.right(response.right().value()); - } - Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null); - if (createResponse.isRight()) { - return Either.right(createResponse.right().value()); - } else { - ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED); - ASDCKpiApi.countImportResourcesKPI(); - return Either.left(resourcePair); - - } - } - - public boolean isResourceExist(String resourceName) { - Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName); - return latestByName.isLeft(); - } - - private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) { - String lockedResourceId = oldResource.getUniqueId(); - log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState()); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null; - try { - if (needLock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - } - - Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false); - if (prepareResourceForUpdate.isRight()) { - ResponseFormat responseFormat = prepareResourceForUpdate.right().value(); - log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage()); - componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(prepareResourceForUpdate.right().value()); - return result; - } - oldResource = prepareResourceForUpdate.left().value(); - - mergeOldResourceMetadataWithNew(oldResource, newResource); - - Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - if (validateFieldsResponse.isRight()) { - result = Either.right(validateFieldsResponse.right().value()); - return result; - } - - validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); - if (validateFieldsResponse.isRight()) { - return Either.right(validateFieldsResponse.right().value()); - } - - // contact info normalization - newResource.setContactId(newResource.getContactId().toLowerCase()); - // non-updatable fields - newResource.setCreatorUserId(user.getUserId()); - newResource.setCreatorFullName(user.getFullName()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setLastUpdaterFullName(user.getFullName()); - newResource.setUniqueId(oldResource.getUniqueId()); - newResource.setVersion(oldResource.getVersion()); - newResource.setInvariantUUID(oldResource.getInvariantUUID()); - newResource.setLifecycleState(oldResource.getLifecycleState()); - newResource.setUUID(oldResource.getUUID()); - newResource.setNormalizedName(oldResource.getNormalizedName()); - newResource.setSystemName(oldResource.getSystemName()); - if (oldResource.getCsarUUID() != null) { - newResource.setCsarUUID(oldResource.getCsarUUID()); - } - if (oldResource.getImportedToscaChecksum() != null) { - newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); - } - newResource.setAbstract(oldResource.isAbstract()); - - if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) { - newResource.setDerivedFrom(oldResource.getDerivedFrom()); - } - // TODO rhalili: handle artifacts here (delete from old resource and - // add for new) - // TODO rbetzer: remove after migration - in case of resources - // created without tosca artifacts - add the placeholders - if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { - setToscaArtifactsPlaceHolders(newResource, user); - } - Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource); - - if (overrideResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); - componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - return result; - } - - log.debug("Resource updated successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - - ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK); - result = Either.left(resourcePair); - return result; - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } else if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - if (needLock == true) { - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - } - - } - - /** - * Merge old resource with new. Keep old category and vendor name without change - * - * @param oldResource - * @param newResource - */ - private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { - - // keep old category and vendor name without change - // merge the rest of the resource metadata - if (newResource.getTags() == null || newResource.getTags().isEmpty()) { - newResource.setTags(oldResource.getTags()); - } - - if (newResource.getDescription() == null) { - newResource.setDescription(oldResource.getDescription()); - } - - if (newResource.getVendorRelease() == null) { - newResource.setVendorRelease(oldResource.getVendorRelease()); - } - - if (newResource.getResourceVendorModelNumber() == null) { - newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); - } - - if (newResource.getContactId() == null) { - newResource.setContactId(oldResource.getContactId()); - } - - newResource.setCategories(oldResource.getCategories()); - newResource.setVendorName(oldResource.getVendorName()); - } - - private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) { - - Either<Resource, ResponseFormat> result = Either.left(latestResource); - // check if user can edit resource - if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) { - // checkout - Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock); - result = changeState; - } - - return result; - } - - public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { - - Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - eitherValidation = validateResourceType(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setContactId(resource.getContactId().toLowerCase()); - if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { - String resourceSystemName; - if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){ - resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); - } else { - resourceSystemName = resource.getSystemName(); - } - resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); - } - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - // TODO - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - resource.setInvariantUUID(invariantUUID); - - return Either.left(resource); - } - - private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getResourceType() == null) { - log.debug("Invalid resource type for resource"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - return eitherResult; - } - - private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { - log.debug("validate interface lifecycle Types Exist"); - Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator(); - while (intItr.hasNext() && eitherResult.isLeft()) { - InterfaceDefinition interfaceDefinition = intItr.next(); - String intType = interfaceDefinition.getUniqueId(); - Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType); - log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); - log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name()); - } - - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - - } - } - return eitherResult; - } - - private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { - log.debug("validate capability Types Exist - capabilities section"); - - for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) { - - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } - - if (resource.getRequirements() != null && resource.getRequirements().size() > 0) { - log.debug("validate capability Types Exist - requirements section"); - for (String type : resource.getRequirements().keySet()) { - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } - - return eitherResult; - } - - // @param typeObject- the object to which the validation is done - private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type, - boolean inTransaction) { - Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); - } - log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = null; - if (type != null) - errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); - else - errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - return eitherResult; - } - - private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, - Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) { - Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey()); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); - } - log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey()); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); - if (capabilityTypeDefinition.getProperties() != null) { - for (CapabilityDefinition capDef : typeEntry.getValue()) { - List<ComponentInstanceProperty> properties = capDef.getProperties(); - if (properties == null || properties.isEmpty()) { - properties = new ArrayList<ComponentInstanceProperty>(); - for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); - properties.add(newProp); - } - } else { - for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { - PropertyDefinition porpFromDef = prop.getValue(); - List<ComponentInstanceProperty> propsToAdd = new ArrayList<>(); - for (ComponentInstanceProperty cip : properties) { - if (!cip.getName().equals(porpFromDef.getName())) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); - propsToAdd.add(newProp); - } - } - if (!propsToAdd.isEmpty()) { - properties.addAll(propsToAdd); - } - } - } - capDef.setProperties(properties); - } - } - return eitherResult; - } - - public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - // create resource - - // lock new resource name in order to avoid creation resource with same - // name - if (inTransaction == false) { - Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams); - return Either.right(responseFormat); - } - - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - if (resource.deriveFromGeneric()) { - Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource); - if (genericResourceEither.isRight()) - return genericResourceEither; - } - - Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction); - if (respStatus.isLeft()) { - auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams); - ASDCKpiApi.countCreatedResourcesKPI(); - } else - componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams); - return respStatus; - - } finally { - if (inTransaction == false) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - } - - private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams); - } - - private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) { - // validate resource name uniqueness - log.debug("validate resource name"); - Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (eitherValidation.isRight()) { - log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); - return Either.right(errorResponse); - } - if (eitherValidation.left().value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - return Either.right(errorResponse); - } - - log.debug("send resource {} to dao for create", resource.getName()); - - createArtifactsPlaceHolderData(resource, user); - - // - - // enrich object - if (!isNormative) { - log.debug("enrich resource with creator, version and state"); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setVersion(INITIAL_VERSION); - resource.setHighestVersion(true); - if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) - resource.setAbstract(false); - } - - Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource); - if (createToscaElement.isLeft()) { - return Either.left(createToscaElement.left().value()); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource); - - return Either.right(responseFormat); - } - - private void createArtifactsPlaceHolderData(Resource resource, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String resourceUniqueId = - // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(), - // resource.getResourceVersion()); - - setInformationalArtifactsPlaceHolder(resource, user); - setDeploymentArtifactsPlaceHolder(resource, user); - setToscaArtifactsPlaceHolders(resource, user); - } - - @SuppressWarnings("unchecked") - @Override - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - Resource resource = (Resource) component; - Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<String, ArtifactDefinition>(); - } - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts(); - if (deploymentResourceArtifacts != null) { - Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator(); - while (iterator.hasNext()) { - Entry<String, Object> currEntry = iterator.next(); - boolean shouldCreateArtifact = true; - Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue(); - Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); - if (object != null) { - List<String> artifactTypes = (List<String>) object; - if (!artifactTypes.contains(resource.getResourceType().name())) { - shouldCreateArtifact = false; - continue; - } - } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey()); - } - if (shouldCreateArtifact) { - if (artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - } - } - resource.setDeploymentArtifacts(artifactMap); - } - - @SuppressWarnings("unchecked") - private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { - Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<String, ArtifactDefinition>(); - } - String resourceUniqueId = resource.getUniqueId(); - List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory(); - List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType(); - Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts(); - List<CategoryDefinition> categories = resource.getCategories(); - boolean isCreateArtifact = true; - if (exludeResourceCategory != null) { - String category = categories.get(0).getName(); - for (String exlude : exludeResourceCategory) { - if (exlude.equalsIgnoreCase(category)) { - isCreateArtifact = false; - break; - } - } - - } - if (isCreateArtifact && exludeResourceType != null) { - String resourceType = resource.getResourceType().name(); - for (String type : exludeResourceType) { - if (type.equalsIgnoreCase(resourceType)) { - isCreateArtifact = false; - break; - } - } - - } - - if (informationalResourceArtifacts != null && isCreateArtifact) { - Set<String> keys = informationalResourceArtifacts.keySet(); - for (String informationalResourceArtifactName : keys) { - Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName); - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - } - } - resource.setArtifacts(artifactMap); - } - - /** - * deleteResource - * - * @param resourceId - * @param user - * @return - */ - public ResponseFormat deleteResource(String resourceId, User user) { - ResponseFormat responseFormat; - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - - Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {}", resourceId); - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); - } - - Resource resource = resourceStatus.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - - result = markComponentToDelete(resource); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - - // Resource resource = null; - Resource resource = null; - StorageOperationStatus result = StorageOperationStatus.OK; - try { - - Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {} version {}", resourceName, version); - return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); - } - - resource = resourceStatus.left().value(); - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - if (resource != null) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - try { - result = markComponentToDelete(resource); - if (!result.equals(StorageOperationStatus.OK)) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - return responseFormat; - } - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - return responseFormat; - } - - public Either<Resource, ResponseFormat> getResource(String resourceId, User user) { - - if (user != null) { - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - } - - // IResourceOperation dataModel = getResourceOperation(); - Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId); - if (storageStatus.isRight()) { - log.debug("failed to get resource by id {}", resourceId); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId)); - } - if(!(storageStatus.left().value() instanceof Resource)){ - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); - } - return Either.left(storageStatus.left().value()); - - } - - public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); - if (getResource.isRight()) { - log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); - } - return Either.left(getResource.left().value()); - } - - /** - * updateResourceMetadata - * - * @param user - modifier data (userId) - * @param inTransaction TODO - * @param resourceIdToUpdate - the resource identifier - * @param newResource - * @return Either<Resource, responseFormat> - */ - public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) { - - Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // IResourceOperation dataModel = getResourceOperation(); - log.debug("Get resource with id {}", resourceIdToUpdate); - boolean needToUnlock = false; - boolean rollbackNeeded = true; - - try { - // Either<Resource, StorageOperationStatus> storageStatus = - // dataModel.getResource_tx(resourceIdToUpdate, false); - if (currentResource == null) { - Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate); - if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - - currentResource = storageStatus.left().value(); - } - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // lock resource - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate); - log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); - return Either.right(responseFormat); - } - - needToUnlock = true; - - // critical section starts here - // convert json to object - - // Update and updated resource must have a non-empty "derivedFrom" - // list - // This code is not called from import resources, because of root - // VF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(currentResource)) { - Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null); - if (derivedFromNotEmptyEither.isRight()) { - log.debug("for updated resource {}, derived from field is empty", newResource.getName()); - return Either.right(derivedFromNotEmptyEither.right().value()); - } - - derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null); - if (derivedFromNotEmptyEither.isRight()) { - log.debug("for current resource {}, derived from field is empty", currentResource.getName()); - return Either.right(derivedFromNotEmptyEither.right().value()); - } - } else { - newResource.setDerivedFrom(null); - } - - Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true); - if (dataModelResponse.isRight()) { - log.debug("failed to update resource metadata!!!"); - rollbackNeeded = true; - return Either.right(dataModelResponse.right().value()); - } - - log.debug("Resource metadata updated successfully!!!"); - rollbackNeeded = false; - return Either.left(dataModelResponse.left().value()); - - } finally { - if (!inTransaction) { - if (rollbackNeeded) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - - if (needToUnlock) { - graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - } - } - } - - private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){ - if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){ - if (log.isInfoEnabled()) - log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" ); - return Either.right(false); - } - List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList()); - for ( GroupDefinition group : list) { - if ( group!=null && group.isSamePrefix( replacePattern ) ){ - String prefix = group.getName().substring( 0, replacePattern.length() ); - String newGroupName = group.getName().replaceFirst(prefix , with); - group.setName(newGroupName); - //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id - //group.setUniqueId(newUid); - } - } - return Either.left(list); - } - - private boolean isComponentNameChanged(Resource newResource,Resource oldResource){ - if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional - String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - return !oldName.equals(futureName); - } - return false; - } - - private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { - //region -> Update groups name for newResource - if ( isComponentNameChanged( currentResource , newResource) ){ - String replacePattern = Optional.ofNullable( //get currentResource name from metadata - Optional.ofNullable( Optional.ofNullable( currentResource ) - .orElse(null).getComponentMetadataDefinition() ) - .orElse(null).getMetadataDataDefinition() ) - .orElse(null).getName(); - String with = Optional.ofNullable( //get newResource name from metadata - Optional.ofNullable( Optional.ofNullable( newResource ) - .orElse(null).getComponentMetadataDefinition() ) - .orElse(null).getMetadataDataDefinition() ) - .orElse(null).getName(); - if ( with != null && replacePattern != null ){ - Either<List<GroupDefinition>,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups()); - if (result.isLeft()) - newResource.setGroups( (List<GroupDefinition>)result.left().value() ); - } - } - //endregion - - Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); - if (validateResourceFields.isRight()) { - return Either.right(validateResourceFields.right().value()); - } - // Setting last updater and uniqueId - newResource.setContactId(newResource.getContactId().toLowerCase()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setUniqueId(resourceIdToUpdate); - // Cannot set highest version through UI - newResource.setHighestVersion(currentResource.isHighestVersion()); - newResource.setCreationDate(currentResource.getCreationDate()); - - Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction); - - if (processUpdateOfDerivedFrom.isRight()) { - log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); - return Either.right(processUpdateOfDerivedFrom.right().value()); - } - - log.debug("send resource {} to dao for update", newResource.getUniqueId()); - if (newResource!=null && newResource.getGroups()!=null){ - for ( GroupDefinition group : newResource.getGroups() ){ - if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null) - groupBusinessLogic.validateAndUpdateGroupMetadata( - newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() , - user, - ComponentTypeEnum.RESOURCE_INSTANCE, - group, - true , - false) ; - } - } - Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource); - - if (dataModelResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); - return Either.right(responseFormat); - } else if (dataModelResponse.left().value() == null) { - log.debug("No response from updateResource"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(dataModelResponse.left().value()); - } - - /** - * validateResourceFieldsBeforeCreate - * - * @param user - modifier data (userId) - * @param dataModel - IResourceOperation for resource crud - * @param resource - Resource object to validate - * @return Either<Boolean, ErrorResponse> - */ - private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum); - if (componentsFieldsValidation.isRight()) { - return componentsFieldsValidation; - } - - // validate name - - /* - * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - * - * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate icon - /* - * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate tags - /* - * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate category - log.debug("validate category"); - Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate vendor name & release & model number - log.debug("validate vendor name"); - eitherValidation = validateVendorName(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate vendor release"); - eitherValidation = validateVendorReleaseName(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate resource vendor model number"); - eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate contact info - /* - * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate cost - log.debug("validate cost"); - eitherValidation = validateCost(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate licenseType - log.debug("validate licenseType"); - eitherValidation = validateLicenseType(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate template (derived from) - log.debug("validate derived from"); - if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { - resource.setDerivedFrom(null); - } - eitherValidation = validateDerivedFromExist(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - // warn about non-updatable fields - checkComponentFieldsForOverrideAttempt(resource); - String currentCreatorFullName = resource.getCreatorFullName(); - if (currentCreatorFullName != null) { - log.warn("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); - if (currentLastUpdaterFullName != null) { - log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = resource.getLastUpdateDate(); - if (currentLastUpdateDate != null) { - log.warn("Resource last update date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = resource.isAbstract(); - if (currentAbstract != null) { - log.warn("Resource abstract is automatically set and cannot be updated"); - } - - return Either.left(true); - } - - /** - * validateResourceFieldsBeforeUpdate - * - * @param currentResource - Resource object to validate - * @param isNested - * @return Either<Boolean, ErrorResponse> - */ - private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); - - // validate resource name - log.debug("validate resource name before update"); - Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate description - log.debug("validate description before update"); - eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate icon before update"); - eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate tags before update"); - eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate vendor name before update"); - eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate resource vendor model number before update"); - eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - - log.debug("validate vendor release before update"); - eitherValidation = validateVendorReleaseName(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate contact info before update"); - eitherValidation = validateContactId(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate derived before update"); - eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate category before update"); - eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // warn about non-updatable fields - String currentResourceVersion = currentResource.getVersion(); - String updatedResourceVersion = updateInfoResource.getVersion(); - - if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { - log.warn("Resource version is automatically set and cannot be updated"); - } - - String currentCreatorUserId = currentResource.getCreatorUserId(); - String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); - - if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { - log.warn("Resource Creator UserId is automatically set and cannot be updated"); - } - - String currentCreatorFullName = currentResource.getCreatorFullName(); - String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); - - if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { - log.warn("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); - String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); - - if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { - log.warn("Resource LastUpdater userId is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); - String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); - - if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { - log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentCreationDate = currentResource.getCreationDate(); - Long updatedCreationDate = updateInfoResource.getCreationDate(); - - if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { - log.warn("Resource Creation date is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = currentResource.getLastUpdateDate(); - Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); - - if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { - log.warn("Resource last update date is automatically set and cannot be updated"); - } - - LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); - LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); - - if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { - log.warn("Resource lifecycle state date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = currentResource.isAbstract(); - Boolean updatedAbstract = updateInfoResource.isAbstract(); - - if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { - log.warn("Resource abstract is automatically set and cannot be updated"); - } - - Boolean currentHighestVersion = currentResource.isHighestVersion(); - Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); - - if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { - log.warn("Resource highest version is automatically set and cannot be updated"); - } - - String currentUuid = currentResource.getUUID(); - String updatedUuid = updateInfoResource.getUUID(); - - if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { - log.warn("Resource UUID is automatically set and cannot be updated"); - } - - ResourceTypeEnum currentResourceType = currentResource.getResourceType(); - ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType(); - - if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) { - log.warn("Resource Type cannot be updated"); - - } - updateInfoResource.setResourceType(currentResource.getResourceType()); - - String currentInvariantUuid = currentResource.getInvariantUUID(); - String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Resource invariant UUID is automatically set and cannot be updated"); - updateInfoResource.setInvariantUUID(currentInvariantUuid); - } - return Either.left(true); - } - - /* - * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName(); - * - * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } - * - * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); - * } - * - * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, - * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName( - * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ; - * - * return Either.left(true); } - */ - - private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { - String resourceNameUpdated = updateInfoResource.getName(); - String resourceNameCurrent = currentResource.getName(); - if (resourceNameCurrent.equals(resourceNameUpdated)) - return true; - // In case of CVFC type we should support the case of old VF with CVFC instances that were created without the "Cvfc" suffix - return (currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) - && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent))); - } - - private String addCvfcSuffixToResourceName(String resourceName) { - return resourceName+"Cvfc"; - } - - private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) { - String resourceNameUpdated = updateInfoResource.getName(); - if (!isResourceNameEquals(currentResource, updateInfoResource)) { - if (isNested || !hasBeenCertified) { - Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null); - if (validateResourceNameResponse.isRight()) { - ResponseFormat errorResponse = validateResourceNameResponse.right().value(); - return Either.right(errorResponse); - } - validateResourceNameResponse = validateResourceNameExists(updateInfoResource); - if (validateResourceNameResponse.isRight()) { - ResponseFormat errorResponse = validateResourceNameResponse.right().value(); - return Either.right(errorResponse); - } - currentResource.setName(resourceNameUpdated); - currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); - currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); - - } else { - log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String iconUpdated = updateInfoResource.getIcon(); - String iconCurrent = currentResource.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null); - if (validateIcon.isRight()) { - ResponseFormat errorResponse = validateIcon.right().value(); - return Either.right(errorResponse); - } - } else { - log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String vendorNameUpdated = updateInfoResource.getVendorName(); - String vendorNameCurrent = currentResource.getVendorName(); - if (!vendorNameCurrent.equals(vendorNameUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null); - if (validateVendorName.isRight()) { - ResponseFormat errorResponse = validateVendorName.right().value(); - return Either.right(errorResponse); - } - } else { - log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { - String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); - String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); - if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { - Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null); - if (validateResourceVendorModelNumber.isRight()) { - ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value(); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) { - Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction); - if (validateCategoryName.isRight()) { - ResponseFormat errorResponse = validateCategoryName.right().value(); - return Either.right(errorResponse); - } - if (hasBeenCertified) { - CategoryDefinition currentCategory = currentResource.getCategories().get(0); - SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0); - CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0); - SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0); - if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) { - log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - - List<String> currentDerivedFrom = currentResource.getDerivedFrom(); - List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } - - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); - - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null); - if (validateDerivedFromExistsEither.isRight()) { - return validateDerivedFromExistsEither; - } - } else { - Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null); - - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } else { - // For derived from, we must know whether it was actually changed, - // otherwise we must do no action. - // Due to changes it inflicts on data model (remove artifacts, - // properties...), it's not like a flat field which can be - // overwritten if not changed. - // So we must indicate that derived from is not changed - updateInfoResource.setDerivedFrom(null); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - - List<String> currentDerivedFrom = currentResource.getDerivedFrom(); - List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } - - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); - - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null); - if (validateDerivedFromExistsEither.isRight()) { - return validateDerivedFromExistsEither; - } - } else { - Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null); - - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { - - if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { - return Either.left(true); - } - - // IResourceOperation resourceOperation = getResourceOperation(); - - String templateName = resource.getDerivedFrom().get(0); - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); - log.debug("request to data model failed with error: {}", storageStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } else if (!dataModelResponse.left().value()) { - log.info("resource template with name: {}, does not exists", templateName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - - return Either.right(responseFormat); - - } - return Either.left(true); - } - - // Tal G for extending inheritance US815447 - private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) { - // If updated resource is not deriving, should fail validation - /* - * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); } - */ - // If current resource is deriving from certain type and it is updated to not deriving, should fail validation - /* - * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); } - */ - String currentTemplateName = currentResource.getDerivedFrom().get(0); - String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); - log.debug("request to data model failed with error: {}", storageStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - if (!dataModelResponse.left().value()) { - log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); - - return Either.right(responseFormat); - - } - return Either.left(true); - } - - public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) { - log.debug("validate resource derivedFrom field"); - if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { - log.info("derived from (template) field is missing for the resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) { - - Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (resourceOperationResponse.isLeft()) { - if (!resourceOperationResponse.left().value()) { - return Either.left(false); - } else { - log.debug("resource with name: {}, already exists", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - return Either.right(errorResponse); - } - } - log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value())); - return Either.right(errorResponse); - } - - /* - * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags(); - * - * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true); - * - * } - * - * private Either<Boolean, ResponseFormat> validateResourceTags(List<String> tags, String resourceName) { log.debug("validate resource tags"); boolean includesResourceName = false; int tagListSize = 0; if (tags != null && !tags.isEmpty()) { for - * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else { - * log.debug("invalid tag {}", tag); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAG)); } tagListSize += tag.length() + 1; } if (!includesResourceName) { log.debug( "tags must include resource name"); - * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize, - * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); } - * - * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); } - */ - - private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - - List<CategoryDefinition> categories = resource.getCategories(); - if (categories == null || categories.size() == 0) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - if (categories.size() > 1) { - log.debug("Must be only one category for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); - return Either.right(responseFormat); - } - CategoryDefinition category = categories.get(0); - List<SubCategoryDefinition> subcategories = category.getSubcategories(); - if (subcategories == null || subcategories.size() == 0) { - log.debug("Missinig subcategory for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - return Either.right(responseFormat); - } - if (subcategories.size() > 1) { - log.debug("Must be only one sub category for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); - return Either.right(responseFormat); - } - - SubCategoryDefinition subcategory = subcategories.get(0); - - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction); - if (validateCategory.isRight()) { - ResponseFormat responseFormat = validateCategory.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) { - if (category != null && subcategory != null) { - log.debug("validating resource category {} against valid categories list", category); - Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); - if (categories.isRight()) { - log.debug("failed to retrive resource categories from Titan"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value()); - return Either.right(responseFormat); - } - List<CategoryDefinition> categoryList = categories.left().value(); - for (CategoryDefinition cat : categoryList) { - if (cat.getName().equals(category.getName())) { - for (SubCategoryDefinition subcat : cat.getSubcategories()) { - if (subcat.getName().equals(subcategory.getName())) { - return Either.left(true); - } - } - log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - } - log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - return Either.left(false); - } - - public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) { - String vendorRelease = resource.getVendorRelease(); - - log.debug("validate vendor relese name"); - if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { - log.info("vendor relese name is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease); - if (validateVendorReleaseResponse.isRight()) { - ResponseFormat responseFormat = validateVendorReleaseResponse.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateVendorReleaseResponse; - } - - public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) { - if (vendorRelease != null) { - if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { - log.info("vendor release exceds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateVendorRelease(vendorRelease)) { - log.info("vendor release is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - - } - - private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) { - String vendorName = resource.getVendorName(); - if (!ValidationUtils.validateStringNotEmpty(vendorName)) { - log.info("vendor name is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName); - if (validateVendorNameResponse.isRight()) { - ResponseFormat responseFormat = validateVendorNameResponse.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateVendorNameResponse; - - } - - private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) { - String resourceVendorModelNumber = resource.getResourceVendorModelNumber(); - Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber); - if (validateResourceVendorModelNumber.isRight()) { - ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateResourceVendorModelNumber; - - } - - - private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) { - if (vendorName != null) { - if (!ValidationUtils.validateVendorNameLength(vendorName)) { - log.info("vendor name exceds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateVendorName(vendorName)) { - log.info("vendor name is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); - return Either.right(errorResponse); - } - return Either.left(true); - - } - return Either.left(false); - - } - - private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) { - if (resourceVendorModelNumber.equals("")) { - return Either.left(true); - } else { - if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) { - log.info("resource vendor model number exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - return Either.right(errorResponse); - } - // resource vendor model number is currently validated as vendor name - if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) { - log.info("resource vendor model number is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - - /* - * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) { - * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse, - * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description); - * - * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); } - * - * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return - * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); } - * - * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return - * Either.left(false); } - */ - - /* - * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId(); - * - * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; } - * - * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse = - * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); - * - * } - */ - - /* - * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon(); - * - * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, - * null); } return validateIcon; - * - * } - * - * public Either<Boolean, ResponseFormat> validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse = - * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); - * - * } - */ - - private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) { - String cost = resource.getCost(); - if (cost != null) { - - if (!ValidationUtils.validateCost(cost)) { - log.debug("resource cost is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) { - log.debug("validate licenseType"); - String licenseType = resource.getLicenseType(); - if (licenseType != null) { - List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes(); - if (!licenseTypes.contains(licenseType)) { - log.debug("License type {} isn't configured"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - if (actionEnum != null) { - // In update case, no audit is required - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return Either.right(responseFormat); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) { - Either<Operation, ResponseFormat> deleteArtifactByInterface = null; - if (updatedResource.getDerivedFrom() != null) { - log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); - log.debug("1. Removing interface artifacts from graph"); - // Remove all interface artifacts of resource - String resourceId = updatedResource.getUniqueId(); - Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces(); - - if (interfaces != null) { - Collection<InterfaceDefinition> values = interfaces.values(); - for (InterfaceDefinition interfaceDefinition : values) { - String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); - - log.trace("Starting interface artifacts removal for interface type {}", interfaceType); - Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); - if (operations != null) { - for (Entry<String, Operation> operationEntry : operations.entrySet()) { - Operation operation = operationEntry.getValue(); - ArtifactDefinition implementation = operation.getImplementationArtifact(); - if (implementation != null) { - String uniqueId = implementation.getUniqueId(); - log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType); - // only thing that transacts and locks here - deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true); - if (deleteArtifactByInterface.isRight()) { - log.debug("Couldn't remove artifact definition with id {}", uniqueId); - if (!inTransaction) { - titanDao.rollback(); - } - return Either.right(deleteArtifactByInterface.right().value()); - } - } else { - log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey()); - } - } - } else { - log.trace("No operations found for interface type {}", interfaceType); - } - } - } - log.debug("2. Removing properties"); - Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); - - if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { - log.debug("Failed to remove all properties of resource"); - if (!inTransaction) - titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); - } - - } else { - log.debug("Derived from wasn't changed during update"); - } - - if (!inTransaction) - titanDao.commit(); - return Either.left(true); - - } - - /**** Auditing *******************/ - - protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - public ICapabilityTypeOperation getCapabilityTypeOperation() { - return capabilityTypeOperation; - } - - public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } - - public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) { - log.debug("validate resource properties default values"); - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - List<PropertyDefinition> properties = resource.getProperties(); - String type = null; - String innerType = null; - if (properties != null) { - for (PropertyDefinition property : properties) { - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); - eitherResult = Either.right(responseFormat); - break; - } - - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - - type = property.getType(); - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value()); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight().booleanValue()) { - log.info("Invalid inner type for property"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); - eitherResult = Either.right(responseFormat); - break; - } - } - - if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) { - log.info("Invalid default value for property"); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); - } - eitherResult = Either.right(responseFormat); - break; - - } - } - } - return eitherResult; - } - - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return vfComponentInstanceBusinessLogic; - } - - private String getComponentTypeForResponse(Component component) { - String componentTypeForResponse = "SERVICE"; - if (component instanceof Resource) { - componentTypeForResponse = ((Resource) component).getResourceType().name(); - } - return componentTypeForResponse; - } - - private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) { - - Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>(); - Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups); - - Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS); - if (eitherNodesTemlates.isLeft()) { - Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value(); - - if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) { - Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry<String, Object> groupNameValue = nodesNameValue.next(); - - String groupName = groupNameValue.getKey(); - Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue()); - if (eitherNode.isRight()) { - String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName(); - BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); - return Either.right(eitherNode.right().value()); - } else { - GroupDefinition groupDefinition = eitherNode.left().value(); - groups.put(groupName, groupDefinition); - } - } - } - } - - return result; - } - - private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) { - - Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson); - if (inputs.isRight()) { - String message = "Failed when creating inputs: for resource:" + resource.getName(); - BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); - Map<String, InputDefinition> resultMap = new HashMap<>(); - return Either.left(resultMap); - - } - - Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value()); - - return result; - } - - @SuppressWarnings("unchecked") - private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) { - - GroupDefinition groupInfo = new GroupDefinition(); - groupInfo.setName(groupName); - Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo); - - try { - if (groupTemplateJson != null && groupTemplateJson instanceof Map) { - Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson; - String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (!StringUtils.isEmpty(groupType)) { - groupInfo.setType(groupType); - } else { - log.debug("The 'type' member is not found under group {}", groupName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName)); - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) { - Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName()); - if (members != null) { - if (members instanceof List) { - Map<String, String> membersLoaded = new HashMap<>(); - List<?> membersAsList = (List<?>) members; - for (Object member : membersAsList) { - membersLoaded.put(member.toString(), ""); - } - groupInfo.setMembers(membersLoaded); - } else { - log.debug("The 'members' member is not of type list under group {}", groupName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - } - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName()); - - Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - groupInfo.convertFromGroupProperties(regResponse.left().value()); - } - } - - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group"); - log.debug("error when creating group, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - @SuppressWarnings("unchecked") - private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) { - - List<GroupProperty> result = new ArrayList<>(); - - if (properties == null) { - return Either.left(result); - } - - Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - - if (groupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - } - - Map<String, PropertyDefinition> gtProperties = new HashMap<>(); - GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); - - List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties(); - - if (propertiesDef != null) { - gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - } - - if (properties != null) { - - if (properties instanceof Map) { - - Map<String, Object> props = (Map<String, Object>) properties; - for (Entry<String, Object> entry : props.entrySet()) { - - String propName = entry.getKey(); - Object value = entry.getValue(); - - PropertyDefinition gtDefinition = gtProperties.get(propName); - if (gtDefinition == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType)); - } - - ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType()); - - String convertedValue = null; - if (value != null) { - if (type == null || value instanceof Map || value instanceof List) { - convertedValue = gson.toJson(value); - } else { - convertedValue = value.toString(); - } - } - - GroupProperty groupProperty = new GroupProperty(); - groupProperty.setValue(convertedValue); - groupProperty.setName(propName); - - log.trace("After building group property {}", groupProperty); - - result.add(groupProperty); - } - - } - - } - - return Either.left(result); - } - - public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) { - - // validate user - if (user != null) { - Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - } - - // get resource from csar uuid - Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); - if (either.isRight()) { - ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid); - return Either.right(resp); - } - - return Either.left(either.left().value()); - } - - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) { - ResponseFormat responseFormat; - Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>(); - - for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) { - String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType(); - if (!defaultCapabilities.containsKey(capabilityType)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType); - return Either.right(responseFormat); - } else { - CapabilityDefinition defaultCapability; - if(CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())){ - defaultCapability = defaultCapabilities.get(capabilityType).get(0); - } else { - Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId); - if(getFullComponentRes.isRight()){ - log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId); - return Either.right(responseFormat); - } - defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); - } - if(CollectionUtils.isEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){ - log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId); - log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId); - return Either.right(responseFormat); - } - if(CollectionUtils.isNotEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){ - Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, uploadedCapabilitiesEntry.getValue().get(0)); - if (validationRes.isRight()) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value()); - return Either.right(responseFormat); - } - } - List<CapabilityDefinition> validCapabilityList = new ArrayList<>(); - validCapabilityList.add(defaultCapability); - validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList); - } - } - return Either.left(validCapabilitiesMap); - } - - private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { - List<ComponentInstanceProperty> validProperties = new ArrayList<>(); - Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); - List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties(); - for (UploadPropInfo property : uploadedProperties) { - String propertyName = property.getName().toLowerCase(); - String propertyType = property.getType(); - ComponentInstanceProperty validProperty; - if (defaultProperties.containsKey(propertyName)) { - if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) { - return Either.right(propertyName); - } - } - validProperty = new ComponentInstanceProperty(); - validProperty.setName(propertyName); - if (property.getValue() != null) - validProperty.setValue(property.getValue().toString()); - validProperty.setDescription(property.getDescription()); - validProperty.setPassword(property.isPassword()); - validProperties.add(validProperty); - } - defaultCapability.setProperties(validProperties); - return Either.left(true); - } - - private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, - Resource resource, User user) { - - EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); - ; - try { - // add all found Csar artifacts to list to upload - List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList); - List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>(); - List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>(); - for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { - ArtifactDefinition foundArtifact; - - if (!existingArtifactsToHandle.isEmpty()) { - foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); - if (foundArtifact != null) { - if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); - // if current artifact already exists, but has different content, add him to the list to update - artifactsToUpdate.add(currNewArtifact); - } - // remove found artifact from the list of existing artifacts to handle, because it was already handled - existingArtifactsToHandle.remove(foundArtifact); - // and remove found artifact from the list to upload, because it should either be updated or be ignored - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), - currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType()); - AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum()); - artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null); - responseWrapper.setInnerElement(responseFormat); - break; - } - } - } - } - if (responseWrapper.isEmpty()) { - existingArtifactsToHandle.stream() - // add all artifacts which was not detected as artifact to update or to ignore to the list to delete - .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId()))); - } - if (responseWrapper.isEmpty()) { - if (!artifactsToUpload.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); - if (!artifactsToUpdate.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); - if (!artifactsToDelete.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - if (!responseWrapper.isEmpty()) { - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - } - return nodeTypeArtifactsToHandleRes; - } - - - private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { - String actualType; - String actualVfName; - String actualPreviousVfName; - if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){ - actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); - actualType = ResourceTypeEnum.VFC.name(); - } else { - actualVfName = vfResourceName; - actualType = nodeResourceType; - } - - StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); - - if (actualName.startsWith(Constants.ABSTRACT)) { - toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); - } else { - toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); - } - StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); - return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString()); - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - ///////////////////////////////////////// DataModel refactoring///////////////////////////////////////////// - @Override - public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) { - - ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); - - if (resourceResultEither.isRight()) { - if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to found resource with id {} ", resourceId); - Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - - log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); - } - - Resource resource = resourceResultEither.left().value(); - UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn); - return Either.left(dataTransfer); - } - @Override - public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { - Resource resource = (Resource) clonedComponent; - if (ModelConverter.isAtomicComponent(resource.getResourceType())) { - Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade.shouldUpgradeToLatestDerived(resource); - if (shouldUpgradeToLatestDerived.isRight()) { - return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value())); - } - return Either.left(shouldUpgradeToLatestDerived.left().value()); - } else { - return super.shouldUpgradeToLatestDerived(clonedComponent); - } - } - - - -} + @Autowired + private CompositionBusinessLogic compositionBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + @Autowired + private MergeResourceBLFactory mergeResourceBLFactory; + + @Autowired + private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic; + + private Gson gson = new Gson(); + + public CsarOperation getCsarOperation() { + return csarOperation; + } + + public void setCsarOperation(CsarOperation csarOperation) { + this.csarOperation = csarOperation; + } + + public LifecycleBusinessLogic getLifecycleBusinessLogic() { + return lifecycleBusinessLogic; + } + + public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { + this.lifecycleBusinessLogic = lifecycleBusinessLogic; + } + + public IElementOperation getElementDao() { + return elementDao; + } + + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } + + public IUserBusinessLogic getUserAdmin() { + return this.userAdmin; + } + + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } + + public ComponentsUtils getComponentsUtils() { + return this.componentsUtils; + } + + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsBusinessLogic; + } + + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsBusinessLogic = artifactsManager; + } + + public void setPropertyOperation(IPropertyOperation propertyOperation) { + this.propertyOperation = propertyOperation; + } + + public ApplicationDataTypeCache getApplicationDataTypeCache() { + return applicationDataTypeCache; + } + + public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { + this.applicationDataTypeCache = applicationDataTypeCache; + } + + /** + * the method returns a list of all the resources that are certified, the + * returned resources are only abstract or only none abstract according to + * the given param + * + * @param getAbstract + * @param userId TODO + * @return + */ + public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, + HighestFilterEnum highestFilter, String userId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Boolean isHighest = null; + switch (highestFilter) { + case ALL: + break; + case HIGHEST_ONLY: + isHighest = true; + break; + case NON_HIGHEST_ONLY: + isHighest = false; + break; + default: + break; + } + Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade + .getAllCertifiedResources(getAbstract, isHighest); + + if (getResponse.isRight()) { + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value()))); + } + + return Either.left(getResponse.left().value()); + } + + public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, + ResourceTypeEnum resourceTypeEnum, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map<String, Boolean> result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, + User user, Map<String, byte[]> csarUIPayload, String payloadName) { + Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false); + if (createResourceResponse.isRight()) { + return createResourceResponse; + } + + // Creating resource either by DAO or from CSAR + String csarUUID = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + } else { + csarUUID = payloadName; + } + if (csarUUID != null && !csarUUID.isEmpty()) { + // check if VF with the same Csar UUID or with he same name already + // exists + Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade + .validateCsarUuidUniqueness(csarUUID); + if (validateCsarUuidUniquenessRes.isRight()) { + log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, + resource.getSystemName()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value()))); + } + + Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value(); + if (existingResourceRes.intValue() > 0) { + log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", + resource.getSystemName(), csarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, + csarUUID); + componentsUtils.auditResource(errorResponse, user, resource, auditingAction); + return Either.right(errorResponse); + } + + log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); + createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID); + return createResourceResponse; + } + + return createResourceByDao(resource, user, auditingAction, false, false); + } + + public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, + Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) { + Either<Resource, ResponseFormat> updateResourceResponse = null; + Either<Resource, ResponseFormat> validateResourceResponse = null; + Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>(); + String csarUUID = null; + String csarVersion = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + csarVersion = resource.getCsarVersion(); + } else { + csarUUID = payloadName; + } + if (csarUUID != null && !csarUUID.isEmpty()) { + Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId); + if (responseWrapper.isEmpty()) { + validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user); + } + if (responseWrapper.isEmpty()) { + validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user); + } + if (responseWrapper.isEmpty()) { + if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { + overrideImmutableMetadata(oldResource, resource); + } + validateResourceResponse = validateResourceBeforeCreate(resource, user, false); + if (validateResourceResponse.isRight()) { + responseWrapper.setInnerElement(validateResourceResponse.right().value()); + } + } + if (responseWrapper.isEmpty()) { + String oldCsarVersion = oldResource.getCsarVersion(); + log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, + resourceUniqueId); + // (on boarding flow): If the update includes same csarUUID and + // same csarVersion as already in the VF - no need to import the + // csar (do only metadata changes if there are). + if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { + updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, + false); + } else { + updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID); + } + } + } else { + log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, + resource.getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + if (responseWrapper.isEmpty()) { + return updateResourceResponse; + } + return Either.right(responseWrapper.getInnerElement()); + } + + private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, + Resource resource, String csarUUID, User user) { + // (on boarding flow): If the update includes a csarUUID: verify this + // csarUUID is not in use by another VF, If it is - use same error as + // above: + // "Error: The VSP with UUID %1 was already imported for VF %2. Please + // select another or update the existing VF." %1 - csarUUID, %2 - VF + // name + Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); + if (resourceLinkedToCsarRes.isRight()) { + if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { + log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, + resource.getSystemName()); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value()))); + } + } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) + && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, + resourceLinkedToCsarRes.left().value().getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + responseWrapper.setInnerElement(errorResponse); + } + } + + private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, + Resource oldResource, String csarUUID, String resourceUniqueId, User user) { + // (on boarding flow): If the update includes csarUUID which is + // different from the csarUUID of the VF - fail with + // error: "Error: Resource %1 cannot be updated using since it is linked + // to a different VSP" %1 - VF name + String oldCsarUUID = oldResource.getCsarUUID(); + if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { + log.debug( + "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", + resourceUniqueId, csarUUID, oldCsarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + responseWrapper.setInnerElement(errorResponse); + } + } + + private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) { + Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId); + if (oldResourceRes.isRight()) { + log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, + oldResourceRes.right().value()); + responseWrapper.setInnerElement(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value()))); + return null; + } + return oldResourceRes.left().value(); + } + + private void overrideImmutableMetadata(Resource oldRresource, Resource resource) { + resource.setName(oldRresource.getName()); + resource.setIcon(oldRresource.getIcon()); + resource.setTags(oldRresource.getTags()); + resource.setVendorName(oldRresource.getVendorName()); + resource.setCategories(oldRresource.getCategories()); + resource.setDerivedFrom(oldRresource.getDerivedFrom()); + } + + private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, + User user, AuditingActionEnum updateResource, boolean inTransaction, + Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) { + + // check state + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) { + if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) { + log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", + oldRresource.getLastUpdaterUserId(), user.getUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + String lockedResourceId = oldRresource.getUniqueId(); + List<ArtifactDefinition> createdArtifacts = new ArrayList<>(); + + Either<Map<String, byte[]>, StorageOperationStatus> csar = null; + if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { + csar = csarUIPayload; + } else { + csar = csarOperation.getCsar(csarUUID, user); + } + if (csar.isRight()) { + log.debug("Failed to get csar for casrUUID{} ", csarUUID); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value()))); + } + + Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, + user, csarUUID, csar); + if (toscaYamlCsarStatus.isRight()) { + return Either.right(toscaYamlCsarStatus.right().value()); + } + Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), + csarUUID, componentsUtils); + if (checksum.isRight()) { + log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value()); + return Either.right(checksum.right().value()); + } + if (!checksum.left().value().equals( + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) { + log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID, + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition() + .getImportedToscaChecksum(), + checksum.left().value()); + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition() + .setImportedToscaChecksum(checksum.left().value()); + } + + Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, + "update Resource From Csar"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + + String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); + CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, + true); + Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo); + Either<Resource, ResponseFormat> result = null; + + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, oldRresource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + return result; + } + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes + .left().value(); + try { + result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, yamlFileName, + yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); + + } finally { + if (result == null || result.isRight()) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + return result; + + } + + private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource, + AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts, + String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + String nodeName, boolean isNested) { + Either<Resource, ResponseFormat> result; + Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither; + boolean inTransaction = true; + boolean shouldLock = false; + + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate; + Resource preparedResource; + Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml( + yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), + nodeTypesInfo, nodeName); + if (uploadComponentInstanceInfoMap.isRight()) { + ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, updateResource); + result = Either.right(responseFormat); + return result; + } + + Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value() + .getInstances(); + + prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), + inTransaction, shouldLock, isNested); + if (prepareForUpdate.isRight()) { + log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); + result = Either.right(prepareForUpdate.right().value()); + return result; + } + preparedResource = prepareForUpdate.left().value().left; + + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); + + Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource); + if (genericResourceEither.isRight()) { + log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value()); + ResponseFormat responseFormat = genericResourceEither.right().value(); + componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + return Either.right(responseFormat); + } + + parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, + shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); + if (parseNodeTypeInfoYamlEither.isRight()) { + ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + + Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); + Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, + csarInfo.getModifier(), inputs, inTransaction); + if (createInputsOnResource.isRight()) { + log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value()); + ResponseFormat responseFormat = createInputsOnResource.right().value(); + componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + preparedResource = createInputsOnResource.left().value(); + + Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances( + csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, + csarInfo.getCreatedNodes()); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create resource instances status is {}", + createResourcesInstancesEither.right().value()); + ResponseFormat responseFormat = createResourcesInstancesEither.right().value(); + componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + preparedResource = createResourcesInstancesEither.left().value(); + + createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, + preparedResource, instances); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create relation between resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = Either.right(createResourcesInstancesEither.right().value()); + return result; + } + + preparedResource = createResourcesInstancesEither.left().value(); + + Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), + preparedResource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { + + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + // add groups to resource + Map<String, GroupDefinition> groups; + + if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left().value(); + } else { + groups = uploadComponentInstanceInfoMap.left().value().getGroups(); + } + Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, + csarInfo.getModifier(), groups); + if (updatedGroupsOnResource.isRight()) { + + return updatedGroupsOnResource; + } + preparedResource = updatedGroupsOnResource.left().value(); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToHandle); + + Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, + csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (updateArtifactsEither.isRight()) { + log.debug("failed to update artifacts {}", updateArtifactsEither.right().value()); + result = Either.right(updateArtifactsEither.right().value()); + return result; + } + preparedResource = updateArtifactsEither.left().value(); + + ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource); + if (mergingPropsAndInputsStatus != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, + preparedResource); + return Either.right(responseFormat); + } + + Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic + .setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); + result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) + : Either.left(preparedResource); + + return result; + + } + + private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts, + String yamlFileName, CsarInfo csarInfo, Resource preparedResource, + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { + + String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName(); + Resource resource = preparedResource; + + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts + .getNodeTypesArtifactsToHandle(); + if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) { + if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) { + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = + handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); + if (handleNodeTypeArtifactsRes.isRight()) { + return Either.right(handleNodeTypeArtifactsRes.right().value()); + } + } + } else { + Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); + log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); + if (createdCsarArtifactsEither.isRight()) { + return createdCsarArtifactsEither; + + } + resource = createdCsarArtifactsEither.left().value(); + } + return Either.left(resource); + } + + private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { + Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory + .getInstance(oldResource, newResource); + if (mergeResourceBLEither.isRight()) { + return mergeResourceBLEither.right().value(); + } + MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value(); + return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource); + } + + private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) { + Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) { + return genericResourceEither; + } + if (resource.shouldGenerateInputs()) { + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + } + return genericResourceEither; + } + + private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle( + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { + + Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils + .extractVfcsArtifactsFromCsar(csarInfo.getCsar()); + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>(); + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes; + + try { + nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); + Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, + oldResource.getName(), csarInfo); + Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes; + EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null; + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", + oldResource.getName(), csarInfo.getCsarUUID()); + + for (Entry<String, ImmutablePair<String, String>> currVfcToscaNameEntry : extractedVfcToscaNames + .entrySet()) { + String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft(); + String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight(); + String currNamespace = currVfcToscaNameEntry.getKey(); + log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName); + + Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade + .getLatestByToscaResourceName(currVfcToscaName); + Resource curNodeType = null; + if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { + curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName); + } + if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, + curVfcRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), + csarInfo.getCsarUUID()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, AuditingActionEnum.CREATE_RESOURCE); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + break; + } else if (curVfcRes.isLeft()) { + curNodeType = curVfcRes.left().value(); + } + if (!MapUtils.isEmpty(extractedVfcsArtifacts)) { + List<ArtifactDefinition> currArtifacts = new ArrayList<>(); + if (extractedVfcsArtifacts.containsKey(currNamespace)) { + handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace)); + } + curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); + if (curNodeTypeArtifactsToHandleRes.isRight()) { + nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value()); + break; + } + curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value(); + + } else if (curNodeType != null) { + // delete all artifacts if have not received artifacts from + // csar + curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); + // delete all informational artifacts + artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream() + .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(Collectors.toList())); + // delete all deployment artifacts + artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); + if (!artifactsToDelete.isEmpty()) { + curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) { + nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); + } + return nodeTypesArtifactsToHandleRes; + } + + private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle( + Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) { + + Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null; + EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null; + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + try { + List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts); + List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>(); + List<ArtifactDefinition> artifactsToDelete = new ArrayList<>(); + if (curNodeType != null) { + Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>(); + if (curNodeType.getDeploymentArtifacts() != null) { + existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); + } + if (curNodeType.getArtifacts() != null) { + existingArtifacts + .putAll(curNodeType.getArtifacts().entrySet().stream() + .filter(e -> e.getValue() + .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); + } + for (ArtifactDefinition currNewArtifact : extractedArtifacts) { + ArtifactDefinition foundArtifact; + + if (!existingArtifacts.isEmpty()) { + foundArtifact = existingArtifacts.values().stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() + .orElse(null); + if (foundArtifact != null) { + if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) { + if (!foundArtifact.getArtifactChecksum() + .equals(currNewArtifact.getArtifactChecksum())) { + foundArtifact.setPayload(currNewArtifact.getPayloadData()); + foundArtifact.setPayloadData( + Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum(GeneralUtility + .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); + artifactsToUpdate.add(foundArtifact); + } + existingArtifacts.remove(foundArtifact.getArtifactLabel()); + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", + currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), + foundArtifact.getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + artifactsToDelete.addAll(existingArtifacts.values()); + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + /** + * Changes resource life cycle state to checked out + * + * @param resource + * @param user + * @param inTransaction + * @return + */ + private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) { + Either<Resource, ResponseFormat> checkoutResourceRes; + try { + if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "************* Going to change life cycle state of resource {} to not certified checked out. ", + resource.getName()); + Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState( + resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("certification on import", + LifecycleChanceActionEnum.CREATE_FROM_CSAR), + inTransaction, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", + resource.getComponentType().getNodeType(), resource.getUniqueId(), + checkoutRes.right().value().getStatus()); + checkoutResourceRes = Either.right(checkoutRes.right().value()); + } else { + checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); + } + } else { + checkoutResourceRes = Either.left(resource); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + checkoutResourceRes = Either.right(responseFormat); + log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), + e); + } + return checkoutResourceRes; + } + + /** + * Handles Artifacts of NodeType + * + * @param nodeTypeResource + * @param nodeTypeArtifactsToHandle + * @param user + * @param inTransaction + * @return + */ + public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) { + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes; + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null; + Either<Resource, ResponseFormat> changeStateResponse; + try { + changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); + if (changeStateResponse.isRight()) { + return Either.right(changeStateResponse.right().value()); + } + nodeTypeResource = changeStateResponse.left().value(); + + List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>(); + log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); + for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle + .entrySet()) { + ArtifactOperationEnum curOperation = curOperationEntry.getKey(); + List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue(); + if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { + log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), + nodeTypeResource.getName()); + handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic + .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, + createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, + ignoreLifecycleState, curOperation), + false, inTransaction); + if (handleNodeTypeArtifactsRequestRes.isRight()) { + handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); + break; + } + if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { + createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + } + if (handleNodeTypeArtifactsRes == null) { + handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleNodeTypeArtifactsRes = Either.right(responseFormat); + log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); + } + return handleNodeTypeArtifactsRes; + } + + private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, + String vfResourceName, CsarInfo csarInfo) { + Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>(); + + Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo); + if (!nodes.isEmpty()) { + Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator(); + while (nodesNameEntry.hasNext()) { + Entry<String, Object> nodeType = nodesNameEntry.next(); + ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName( + ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + vfcToscaNames.put(nodeType.getKey(), toscaResourceName); + } + } + for (NodeTypeInfo cvfc : nodeTypesInfo.values()) { + vfcToscaNames.put(cvfc.getType(), + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); + } + return vfcToscaNames; + } + + private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) { + Map<String, Object> nodes = new HashMap<>(); + for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) { + extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); + } + extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); + return nodes; + } + + private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) { + Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (eitherNodeTypes.isLeft()) { + nodes.putAll(eitherNodeTypes.left().value()); + } + } + + public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, + Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) { + log.trace("************* created successfully from YAML, resource TOSCA "); + + Either<Map<String, byte[]>, StorageOperationStatus> csar = null; + if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { + csar = csarUIPayload; + } else { + csar = csarOperation.getCsar(csarUUID, user); + } + + Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, + csarUUID, csar); + if (toscaYamlCsarStatus.isRight()) { + return Either.right(toscaYamlCsarStatus.right().value()); + } + Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), + csarUUID, componentsUtils); + if (toscaYamlChecksum.isRight()) { + log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, + toscaYamlChecksum.right().value()); + return Either.right(toscaYamlChecksum.right().value()); + } + resource.getComponentMetadataDefinition().getMetadataDataDefinition() + .setImportedToscaChecksum(toscaYamlChecksum.left().value()); + + String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); + + CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, + false); + Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo); + Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, resource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + return Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + } + Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, + yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, + null); + if (createResourceFromYaml.isRight()) { + log.debug("Couldn't create resource from YAML"); + return Either.right(createResourceFromYaml.right().value()); + } + + Resource vfResource = createResourceFromYaml.left().value(); + log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", + vfResource.getToscaResourceName()); + return Either.left(vfResource); + } + + private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) { + Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>(); + List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>(); + for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) { + extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry); + } + if (CollectionUtils.isNotEmpty(globalSubstitutes)) { + setDerivedFrom(nodeTypesInfo, globalSubstitutes); + } + markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo); + return nodeTypesInfo; + } + + @SuppressWarnings("unchecked") + private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, + List<Entry<String, byte[]>> globalSubstitutes) { + for (Map.Entry<String, byte[]> entry : globalSubstitutes) { + String yamlFileContents = new String(entry.getValue()); + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents); + Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + if (nodeTypesEither.isLeft()) { + Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value(); + for (Entry<String, Object> nodeType : nodeTypes.entrySet()) { + Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue(); + if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) { + if (nodeTypesInfo.containsKey(nodeType.getKey())) { + NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey()); + List<String> derivedFrom = new ArrayList<>(); + derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName())); + nodeTypeInfo.setDerivedFrom(derivedFrom); + } + } + } + } + } + } + + @SuppressWarnings("unchecked") + private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo, + List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) { + if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) { + if (!isGlobalSubstitute(entry.getKey())) { + String yamlFileContents = new String(entry.getValue()); + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents); + Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement( + mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP); + if (substitutionMappingsEither.isLeft()) { + Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left() + .value(); + if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) { + NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); + nodeTypeInfo.setType( + (String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName())); + nodeTypeInfo.setTemplateFileName(entry.getKey()); + nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate); + nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo); + } + } + } else { + globalSubstitutes.add(entry); + } + } + } + + @SuppressWarnings("unchecked") + private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) { + Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP); + if (nodeTemplatesEither.isLeft()) { + Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value(); + for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) { + Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue(); + if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName()); + if (nodeTypesInfo.containsKey(type)) { + NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); + nodeTypeInfo.setNested(true); + } + } + } + } + } + + private boolean isGlobalSubstitute(String fileName) { + return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) + || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); + } + + private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, + String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) { + if (csar.isRight()) { + StorageOperationStatus value = csar.right().value(); + log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), + csarUUID, componentsUtils); + if (validateCsarStatus.isRight()) { + ResponseFormat responseFormat = validateCsarStatus.right().value(); + log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + + Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils + .getToscaYaml(csar.left().value(), csarUUID, componentsUtils); + + if (toscaYamlCsarStatus.isRight()) { + ResponseFormat responseFormat = toscaYamlCsarStatus.right().value(); + log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + return toscaYamlCsarStatus; + } + + private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, + boolean inTransaction) { + log.trace("validating resource before create"); + Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, + AuditingActionEnum.CREATE_RESOURCE, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user.copyData(eitherCreator.left().value()); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), + AuditingActionEnum.CREATE_RESOURCE, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + // VF / PNF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(resource)) { + Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, + AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + } + return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); + + } + + // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, + // nodeTypesArtifactsToCreate, true, false, null + private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, + String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { + + List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>(); + log.trace("************* createResourceFromYaml before parse yaml "); + Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml( + yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, + nodeName); + if (parseResourceInfoFromYamlEither.isRight()) { + ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + log.trace("************* createResourceFromYaml after parse yaml "); + ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value(); + log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo); + log.trace("************* createResourceFromYaml before create "); + Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, + parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, + nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + log.trace("************* createResourceFromYaml after create "); + if (createdResourceResponse.isRight()) { + ResponseFormat responseFormat = createdResourceResponse.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + return createdResourceResponse; + + } + + public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, + Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo) { + + Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, + ToscaTagNamesEnum.TOSCA_VERSION); + if (tosca_version.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + return Either.right(responseFormat); + } + Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); + Map<String, Object> mapToConvert = new HashMap<String, Object>(); + mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value()); + Resource vfcCreated = null; + if (eitherNodeTypes.isLeft()) { + Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry<String, Object> nodeType = nodesNameValue.next(); + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null + || nodeTypesArtifactsToHandle.isEmpty() ? null + : nodeTypesArtifactsToHandle.get(nodeType.getKey()); + + if (nodeTypesInfo.containsKey(nodeType.getKey())) { + log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); + Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeType.getKey()); + log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); + if (handleNeatedVfcYaml.isRight()) { + return Either.right(handleNeatedVfcYaml.right().value()); + } + vfcCreated = handleNeatedVfcYaml.left().value(); + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null + && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + log.trace("************* Going to create node {}", nodeType.getKey()); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this + .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, + resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, + csarInfo, true); + log.debug("************* Finished to create node {}", nodeType.getKey()); + + if (resourceCreated.isRight()) { + return Either.right(resourceCreated.right().value()); + } + vfcCreated = resourceCreated.left().value().getLeft(); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), + vfcCreated.getToscaResourceName()); + } + if (vfcCreated != null) { + csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); + } + mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName()); + } + } + return result; + } + + private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName) { + + Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource); + String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); + Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); + + log.debug("************* Going to create node types from yaml {}", yamlName); + Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList( + yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo); + if (createNodeTypesRes.isRight()) { + log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, + createNodeTypesRes.right().value()); + return Either.right(createNodeTypesRes.right().value()); + } + log.debug("************* Finished to create node types from yaml {}", yamlName); + + if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { + log.debug("************* Going to handle complex VFC from yaml {}", yamlName); + handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo, nodeName, yamlName); + } + return handleNestedVfcRes; + } + + private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName) { + + Either<Resource, ResponseFormat> result = null; + Resource oldComplexVfc = null; + Resource newComplexVfc = null; + + Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); + if (buildCvfcRes.isRight()) { + log.debug("Failed to validate complex VFC for node {}. ", nodeName); + result = buildCvfcRes; + } + if (result == null) { + newComplexVfc = buildCvfcRes.left().value(); + Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade + .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { + oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), + nodeName).getRight()); + } + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", + newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } else if (oldComplexVfcRes.isLeft()) { + log.debug("validate derived before update"); + Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate( + oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + if (eitherValidation.isLeft()) { + oldComplexVfc = oldComplexVfcRes.left().value(); + } + } + } + if (result == null) { + result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, + oldComplexVfc, newComplexVfc); + } + if (result.isLeft()) { + newComplexVfc = result.left().value(); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( + "certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); + log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); + result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, + true); + if (result.isRight()) { + log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName()); + } + } + if (result.isLeft()) { + csarInfo.getCreatedNodes().put(nodeName, result.left().value()); + csarInfo.getCvfcToCreateQueue().remove(); + } + return result; + } + + private Either<Resource, ResponseFormat> handleComplexVfc( + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, + List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + + Either<Resource, ResponseFormat> handleComplexVfcRes; + Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); + String yamlContent = new String(csarInfo.getCsar().get(yamlName)); + Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy())); + markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); + if (oldComplexVfc == null) { + handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, + csarInfo, nodesArtifactsToHandle, false, true, nodeName); + if (handleComplexVfcRes.isRight()) { + log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName); + } + } else { + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, + newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + if (handleComplexVfcRes.isRight()) { + log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName); + } + } + return handleComplexVfcRes; + } + + private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, + Map<String, NodeTypeInfo> nodesInfo) { + + Either<Resource, ResponseFormat> result = null; + Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); + log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); + + if (!csarInfo.getCvfcToCreateQueue().contains(nodeName)) { + csarInfo.getCvfcToCreateQueue().add(nodeName); + } else { + log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), + csarInfo.getVfResourceName()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, + csarInfo.getVfResourceName(), complexVfc.getName())); + } + if (result == null) { + result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), + AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); + if (result.isRight()) { + log.debug("Failed to validate complex VFC {}. ", complexVfc.getName()); + } + } + return result; + } + + private String getNodeTypeActualName(String fullName) { + String nameWithouNamespacePrefix = fullName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + return nameWithouNamespacePrefix.substring(resourceType.length()); + } + + private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml( + String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, + Resource resourceVf, boolean needLock, + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { + + Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, + nodeNameValue.getKey(), user); + if (resourceMetaData.isRight()) { + return Either.right(resourceMetaData.right().value()); + } + String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, + resourceMetaData.left().value().getResourceType(), csarInfo); + + Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, + AuditingActionEnum.CHECKIN_RESOURCE, true); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, + nodeNameValue.getKey(), isNested); + } + + private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, + String nodeResourceType, CsarInfo csarInfo) { + // We need to create a Yaml from each node_types in order to create + // resource from each node type using import normative flow. + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + + Map<String, Object> node = new HashMap<>(); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()) + .getLeft(), nodeNameValue.getValue()); + mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); + + return yaml.dumpAsMap(mapToConvert); + } + + public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) { + + Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, + resource, AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + return Either.left(true); + } + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, + UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, + Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + String nodeName, boolean isNested) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", + LifecycleChanceActionEnum.CREATE_FROM_CSAR); + Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this + .validateResourceCreationFromNodeType(resource, creator); + return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, + lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } + + private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, + String nodeName, User user) { + UploadResourceInfo resourceMetaData = new UploadResourceInfo(); + + // validate nodetype name prefix + if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { + log.debug("invalid nodeName:{} does not start with {}.", nodeName, + Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, resourceMetaData.getName(), nodeName); + return Either.right(responseFormat); + } + + String actualName = this.getNodeTypeActualName(nodeName); + String namePrefix = nodeName.replace(actualName, ""); + String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + + // if we import from csar, the node_type name can be + // org.openecomp.resource.abstract.node_name - in this case we always + // create a vfc + if (resourceType.equals(Constants.ABSTRACT)) { + resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); + } + // validating type + if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { + log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), + ResourceTypeEnum.values()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, resourceMetaData.getName(), nodeName); + return Either.right(responseFormat); + } + + // Setting name + resourceMetaData.setName(resourceVf.getSystemName() + actualName); + + // Setting type from name + String type = resourceType.toUpperCase(); + resourceMetaData.setResourceType(type); + + resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); + resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); + resourceMetaData.setContactId(user.getUserId()); + resourceMetaData.setVendorName(resourceVf.getVendorName()); + resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); + + // Setting tag + List<String> tags = new ArrayList<>(); + tags.add(resourceMetaData.getName()); + resourceMetaData.setTags(tags); + + // Setting category + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + resourceMetaData.setCategories(categories); + + return Either.left(resourceMetaData); + } + + private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, + Map<String, NodeTypeInfo> nodesInfo) { + Resource cvfc = new Resource(); + NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); + cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); + cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); + cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); + cvfc.setResourceType(ResourceTypeEnum.CVFC); + cvfc.setAbstract(true); + cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); + cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); + cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); + cvfc.setContactId(csarInfo.getModifier().getUserId()); + cvfc.setCreatorUserId(csarInfo.getModifier().getUserId()); + cvfc.setVendorName(resourceVf.getVendorName()); + cvfc.setVendorRelease(resourceVf.getVendorRelease()); + cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); + cvfc.setToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName) + .getLeft()); + cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + + List<String> tags = new ArrayList<>(); + tags.add(cvfc.getName()); + cvfc.setTags(tags); + + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + cvfc.setCategories(categories); + + cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); + cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + + return cvfc; + } + + private String buildCvfcName(String resourceVfName, String nodeName) { + String nameWithouNamespacePrefix = nodeName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); + return addCvfcSuffixToResourceName(resourceName); + } + + private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, + ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, + List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { + + boolean result = true; + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>(); + + if (shouldLock) { + Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, + "Create Resource"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + return Either.right(responseFormat); + } + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + log.trace("************* createResourceFromYaml before full create resource {}", yamlName); + Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) { + result = false; + return genericResourceEither; + } + Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, + csarInfo.getModifier(), isNormative, inTransaction); + log.trace("************* createResourceFromYaml after full create resource {}", yamlName); + if (createResourcesEither.isRight()) { + result = false; + return createResourcesEither; + } + resource = createResourcesEither.left().value(); + // add groups to resource + log.trace("************* Going to add inputs from yaml {}", yamlName); + if (resource.shouldGenerateInputs()) + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + + Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs(); + Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, + csarInfo.getModifier(), inputs, inTransaction); + if (createInputsOnResource.isRight()) { + result = false; + return createInputsOnResource; + } + resource = createInputsOnResource.left().value(); + log.trace("************* Finish to add inputs from yaml {}", yamlName); + + Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo + .getInstances(); + log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); + + createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, + actionEnum, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypesArtifactsToCreate, nodeName); + log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); + if (createResourcesEither.isRight()) { + result = false; + return createResourcesEither; + } + + resource = createResourcesEither.left().value(); + // validate update vf module group names + Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { + result = false; + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + // add groups to resource + Map<String, GroupDefinition> groups; + log.trace("************* Going to add groups from yaml {}", yamlName); + + if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left().value(); + } else { + groups = parsedToscaYamlInfo.getGroups(); + } + Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, + csarInfo.getModifier(), groups); + if (createGroupsOnResource.isRight()) { + result = false; + return createGroupsOnResource; + } + resource = createGroupsOnResource.left().value(); + log.trace("************* Finished to add groups from yaml {}", yamlName); + + log.trace("************* Going to add artifacts from yaml {}", yamlName); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToCreate); + + Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, + csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (createArtifactsEither.isRight()) { + log.debug("failed to update artifacts {}", createArtifactsEither.right().value()); + return createArtifactsEither; + + } + resource = createArtifactsEither.left().value(); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + return Either.left(resource); + + } finally { + if (!inTransaction) { + if (!result) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); + log.debug("component and all its artifacts were deleted, id = {}", resource.getName()); + } + + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + if (shouldLock) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + } + + private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, + Map<String, GroupDefinition> groups) { + if (groups != null && !groups.isEmpty()) { + Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource( + groups, resource); + + if (mergeGroupsUsingResource.isRight()) { + log.debug("Failed to prepare groups for creation"); + return Either.right(mergeGroupsUsingResource.right().value()); + } + List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value(); + Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, + groupsAsList); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + } else { + return Either.left(resource); + } + Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, + Map<String, GroupDefinition> groups) { + if (groups != null && false == groups.isEmpty()) { + List<GroupDefinition> groupsFromResource = resource.getGroups(); + Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource( + groups, resource); + + if (mergeGroupsUsingResource.isRight()) { + log.debug("Failed to prepare groups for creation"); + return Either.right(mergeGroupsUsingResource.right().value()); + } + List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value(); + List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>(); + List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>(); + List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>(); + if (groupsFromResource != null && !groupsFromResource.isEmpty()) { + for (GroupDefinition group : groupsAsList) { + Optional<GroupDefinition> op = groupsFromResource.stream() + .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + if (op.isPresent()) { + GroupDefinition groupToUpdate = op.get(); + groupToUpdate.setMembers(group.getMembers()); + groupsToUpdate.add(groupToUpdate); + } else { + groupsToCreate.add(group); + } + } + for (GroupDefinition group : groupsFromResource) { + Optional<GroupDefinition> op = groupsAsList.stream() + .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { + + groupsToDelete.add(group); + } + + } + } else + groupsToCreate.addAll(groupsAsList); + Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null; + if (!groupsToCreate.isEmpty()) { + + if (groupsFromResource != null && !groupsFromResource.isEmpty()) { + prepareGroups = groupBusinessLogic.addGroups(resource, + groupsToCreate); + } else { + prepareGroups = groupBusinessLogic.createGroups(resource, + groupsToCreate); + } + + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + if (!groupsToDelete.isEmpty()) { + prepareGroups = groupBusinessLogic.deleteGroups(resource, + groupsToDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { + prepareGroups = groupBusinessLogic.updateGroups(resource, groupsToUpdate); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + } else { + return Either.left(resource); + } + + Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, + Map<String, InputDefinition> inputs, boolean inTransaction) { + List<InputDefinition> resourceProperties = resource.getInputs(); + if ((inputs != null && false == inputs.isEmpty()) + || (resourceProperties != null && false == resourceProperties.isEmpty())) { + + Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, + resource); + if (createInputs.isRight()) { + return Either.right(createInputs.right().value()); + } + } else { + return Either.left(resource); + } + + Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource( + Map<String, GroupDefinition> groups, Resource component) { + + List<GroupDefinition> result = new ArrayList<>(); + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + + if (groups != null) { + Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); + if (validateCyclicGroupsDependencies.isRight()) { + return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies); + } + for (Entry<String, GroupDefinition> entry : groups.entrySet()) { + String groupName = entry.getKey(); + + GroupDefinition groupDefinition = entry.getValue(); + + GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); + updatedGroupDefinition.setMembers(null); + + // get the members of the group + Map<String, String> members = groupDefinition.getMembers(); + if (members != null) { + Set<String> compInstancesNames = members.keySet(); + + if (componentInstances == null || true == componentInstances.isEmpty()) { + String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); + log.debug( + "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", + membersAstString, groupName, component.getNormalizedName()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component))); + } + // Find all component instances with the member names + Map<String, String> memberNames = componentInstances.stream() + .collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> ""))); + Map<String, String> relevantInstances = memberNames.entrySet().stream() + .filter(n -> compInstancesNames.contains(n.getKey())) + .collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue())); + + if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { + + List<String> foundMembers = new ArrayList<>(); + if (relevantInstances != null) { + foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList()); + } + compInstancesNames.removeAll(foundMembers); + String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, + groupName, component.getNormalizedName()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component))); + } + + updatedGroupDefinition.setMembers(relevantInstances); + } + + result.add(updatedGroupDefinition); + } + } + return Either.left(result); + } + + /** + * This Method validates that there is no cyclic group dependencies. meaning + * group A as member in group B which is member in group A + * + * @param allGroups + * @return + */ + private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) { + + Either<Boolean, ResponseFormat> result = Either.left(true); + try { + Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator(); + while (allGroupsItr.hasNext() && result.isLeft()) { + Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next(); + // Fetches a group member A + String groupAName = groupAEntry.getKey(); + // Finds all group members in group A + Set<String> allGroupAMembersNames = new HashSet<>(); + fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); + // If A is a group member of itself found cyclic dependency + if (allGroupAMembersNames.contains(groupAName)) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); + result = Either.right(responseFormat); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(responseFormat); + log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); + } + return result; + } + + /** + * This Method fills recursively the set groupMembers with all the members + * of the given group which are also of type group. + * + * @param groupName + * @param allGroups + * @param allGroupMembers + * @return + */ + private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, + Set<String> allGroupMembers) { + + // Found Cyclic dependency + if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { + return; + } + GroupDefinition groupDefinition = allGroups.get(groupName); + // All Members Of Current Group Resource Instances & Other Groups + Set<String> currGroupMembers = groupDefinition.getMembers().keySet(); + // Filtered Members Of Current Group containing only members which + // are groups + List<String> currGroupFilteredMembers = currGroupMembers.stream(). + // Keep Only Elements of type group and not Resource Instances + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Add Filtered Elements to main Set + peek(innerGroupName -> allGroupMembers.add(innerGroupName)). + // Collect results + collect(Collectors.toList()); + + // Recursively call the method for all the filtered group members + for (String innerGroupName : currGroupFilteredMembers) { + fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); + } + + } + + private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, + Set<String> allGroupMembers) { + + boolean stop = false; + // In Case Not Group Stop + if (!allGroups.containsKey(groupName)) { + stop = true; + } + // In Case Group Has no members stop + if (!stop) { + GroupDefinition groupDefinition = allGroups.get(groupName); + stop = MapUtils.isEmpty(groupDefinition.getMembers()); + + } + // In Case all group members already contained stop + if (!stop) { + final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet(); + Set<String> membersOfTypeGroup = allMembers.stream(). + // Filter In Only Group members + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Collect + collect(Collectors.toSet()); + stop = allGroupMembers.containsAll(membersOfTypeGroup); + } + return stop; + } + + private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, + Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum, + String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, + Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate, + String nodeName) { + + Either<Resource, ResponseFormat> result; + Either<Resource, ResponseFormat> createResourcesInstancesEither; + + log.debug("************* Going to create all nodes {}", yamlName); + Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, + resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, + nodeTypesInfo, csarInfo, nodeName); + log.debug("************* Finished to create all nodes {}", yamlName); + if (createdResourcesFromdNodeTypeMap.isRight()) { + log.debug("failed to resources from node types status is {}", + createdResourcesFromdNodeTypeMap.right().value()); + return Either.right(createdResourcesFromdNodeTypeMap.right().value()); + } + + log.debug("************* Going to create all resource instances {}", yamlName); + createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, + uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes()); + + log.debug("************* Finished to create all resource instances {}", yamlName); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = createResourcesInstancesEither; + return createResourcesInstancesEither; + } + resource = createResourcesInstancesEither.left().value(); + log.debug("************* Going to create all relations {}", yamlName); + createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, + uploadComponentInstanceInfoMap); + + log.debug("************* Finished to create all relations {}", yamlName); + + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create relation between resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = createResourcesInstancesEither; + return result; + } else { + resource = createResourcesInstancesEither.left().value(); + } + + log.debug("************* Going to create positions {}", yamlName); + Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic + .setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); + log.debug("************* Finished to set positions {}", yamlName); + result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource); + + return result; + } + + private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, + List<ArtifactDefinition> artifactsToAdd) { + List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()) + .collect(Collectors.toList()); + artifactsToAdd.stream().forEach(a -> { + if (!vfcArtifactNames.contains(a.getArtifactName())) { + vfcArtifacts.add(a); + } else { + log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName()); + } + }); + + } + + @SuppressWarnings("unchecked") + private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, + String topologyTemplateYaml, boolean needLock, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, + List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, + CsarInfo csarInfo, String nodeName) { + + Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); + for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) { + if (nodeTypeEntry.getValue().isNested()) { + + Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypeEntry.getKey()); + log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); + if (createResourceFromYaml.isRight()) { + return Either.right(createResourceFromYaml.right().value()); + } + } + } + + Map<String, Object> mappedToscaTemplate = null; + if (StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) + && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); + } + if (MapUtils.isEmpty(mappedToscaTemplate)) { + mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml); + } + + Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList( + yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + if (createdNodeTypeFromMainTemplateEither.isRight()) { + ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + // add the created node types to the cache although they are not in the + // graph. + csarInfo.getCreatedNodes().values().stream() + .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource)); + + return result; + } + + private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, + List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction) { + + if (csarInfo.getCsar() != null) { + String vendorLicenseModelId = null; + String vfLicenseModelId = null; + + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { + Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts(); + if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { + for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) { + if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) + vendorLicenseModelId = artifactEntry.getValue().getUniqueId(); + if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) + vfLicenseModelId = artifactEntry.getValue().getUniqueId(); + } + } + + } + // Specific Behavior for license artifacts + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, + ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, + Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, false, shouldLock, + inTransaction); + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, + ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, + Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, + artifactOperation, null, false, shouldLock, inTransaction); + + Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, + createdArtifacts, shouldLock, inTransaction, artifactOperation); + if (eitherCreateResult.isRight()) { + return Either.right(eitherCreateResult.right().value()); + } + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + return Either.right(responseFormat); + + } + resource = eitherGerResource.left().value(); + + Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); + + if (artifacsMetaCsarStatus.isLeft()) { + String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); + String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); + Either<Resource, ResponseFormat> createArtifactsFromCsar; + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); + else + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); + + if (createArtifactsFromCsar.isRight()) { + log.debug("Couldn't create artifacts from artifacts.meta"); + return Either.right(createArtifactsFromCsar.right().value()); + } + + return Either.left(createArtifactsFromCsar.left().value()); + } else { + + return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction); + + } + } + return Either.left(resource); + } + + + private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, + String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, + String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, + ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock, + boolean inTransaction) { + byte[] artifactFileBytes = null; + + if (csarInfo.getCsar().containsKey(artifactPath)) { + artifactFileBytes = csarInfo.getCsar().get(artifactPath); + } + Either<Boolean, ResponseFormat> result = Either.left(true); + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) { + if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, + shouldLock, inTransaction); + if (handleDelete.isRight()) { + result = Either.right(handleDelete.right().value()); + } + return result; + } + + + if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { + operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE); + } + + } + if (artifactFileBytes != null) { + Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName, + artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, + artifactFileBytes, null, isFromCsar); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), vendorLicenseModelJson, operation); + addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + if (eitherNonMetaArtifacts.isRight()) { + BeEcompErrorManager.getInstance() + .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), + ErrorSeverity.WARNING); + return Either.right(eitherNonMetaArtifacts.right().value()); + } + } + return result; + } + + private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) { + return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar; + } + + + private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, + List<ArtifactDefinition> createdArtifacts, + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null + && eitherNonMetaArtifacts.isLeft()) { + Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value(); + if (eitherResult.isLeft()) { + createdArtifacts.add(eitherResult.left().value()); + } + } + } + + + private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, + List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, + ArtifactOperationInfo artifactOperation) { + + Either<Resource, ResponseFormat> resStatus = null; + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + + try { + List<NonMetaArtifactInfo> artifactPathAndNameList = + // Stream of file paths contained in csar + csarInfo.getCsar().entrySet().stream() + // Filter in only VF artifact path location + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) + .matches()) + // Validate and add warnings + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), + collectedWarningMessages)) + // Filter in Non Warnings + .filter(e -> e.isLeft()) + // Convert from Either to NonMetaArtifactInfo + .map(e -> e.left().value()) + // collect to List + .collect(Collectors.toList()); + + Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList); + if (responseFormatEither.isRight()) { + return Either.right(getComponentsUtils().getResponseFormatByArtifactId( + ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value())); + } + + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null; + + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { + vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList); + } else { + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( + resource, artifactPathAndNameList, csarInfo.getModifier()); + + if (findVfCsarArtifactsToHandleRes.isRight()) { + resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); + } + if (resStatus == null) { + vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); + } + } + + + if (resStatus == null && vfCsarArtifactsToHandle != null) { + + for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle + .entrySet()) { + + Optional<ResponseFormat> optionalCreateInDBError = + // Stream of artifacts to be created + currArtifactOperationPair.getValue().stream() + // create each artifact + .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), + e.getArtifactName(), e.getArtifactType().getType(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), + CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + currArtifactOperationPair.getKey()), + createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) + // filter in only error + .filter(e -> e.isRight()). + // Convert the error from either to + // ResponseFormat + map(e -> e.right().value()). + // Check if an error occurred + findAny(); + // Error found on artifact Creation + if (optionalCreateInDBError.isPresent()) { + resStatus = Either.right(optionalCreateInDBError.get()); + break; + } + } + } + if (resStatus == null) { + resStatus = Either.left(resource); + } + } catch (Exception e) { + resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); + } finally { + CsarUtils.handleWarningMessages(collectedWarningMessages); + } + return resStatus; + } + + private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) { + Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); + for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { + if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { + return Either.right(nonMetaArtifactInfo.getArtifactName()); + } + } + return Either.left(true); + } + + private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle( + Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) { + + List<ArtifactDefinition> existingArtifacts = new ArrayList<>(); + // collect all Deployment and Informational artifacts of VF + if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); + } + if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getArtifacts().values()); + } + existingArtifacts = existingArtifacts.stream() + // filter MANDATORY artifacts, LICENSE artifacts and artifacts + // was created from HEAT.meta + .filter(this::isNonMetaArtifact).collect(Collectors.toList()); + + List<String> artifactsToIgnore = new ArrayList<>(); + // collect IDs of Artifacts of VF which belongs to any group + if (resource.getGroups() != null) { + resource.getGroups().stream().forEach(g -> { + if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) + artifactsToIgnore.addAll(g.getArtifacts()); + }); + } + existingArtifacts = existingArtifacts.stream() + // filter artifacts which belongs to any group + .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList()); + return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); + } + + private boolean isNonMetaArtifact(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { + result = false; + } + return result; + } + + private boolean isValidArtifactType(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getArtifactType() == null + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { + result = false; + } + return result; + } + + private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, + Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { + log.debug("createResourceInstancesRelations try to create relations "); + List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); + if (uploadResInstancesMap == null) { + log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName); + BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", + yamlName, ErrorSeverity.ERROR); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return Either.right(responseFormat); + } + + if (componentInstancesList == null || componentInstancesList.isEmpty()) { + log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return Either.right(responseFormat); + } + + log.debug("Before validateAndUpdatePropertyValue"); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", + "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName)); + + } + + Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>(); + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>(); + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>(); + Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>(); + Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>(); + Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>(); + Map<String, Resource> originCompMap = new HashMap<>(); + List<RequirementCapabilityRelDef> relations = new ArrayList<>(); + + Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>(); + + for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { + log.trace("Processing entry: {}", entry); + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + log.trace("Processing component instance: {}", compInstance); + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return Either.right(responseFormat); + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + Resource originResource; + if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { + Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade + .getToscaFullElement(currentCompInstance.getComponentUid()); + if (getOriginResourceRes.isRight()) { + log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", + currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), + getOriginResourceRes); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); + return Either.right(responseFormat); + } + originResource = getOriginResourceRes.left().value(); + originCompMap.put(originResource.getUniqueId(), originResource); + } else { + originResource = originCompMap.get(currentCompInstance.getComponentUid()); + } + if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) + instRequirements.put(currentCompInstance, originResource.getRequirements()); + if (MapUtils.isNotEmpty(originResource.getCapabilities())) { + Map<String, List<CapabilityDefinition>> originCapabilities; + if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { + originCapabilities = new HashMap<>(); + originResource.getCapabilities().entrySet().stream().forEach(e -> { + List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l)) + .collect(Collectors.toList()); + originCapabilities.put(e.getKey(), list); + }); + Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>(); + for (List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()) { + for (UploadCapInfo capability : capabilities) { + if (CollectionUtils.isNotEmpty(capability.getProperties())) { + newPropertiesMap.put(capability.getName(), capability.getProperties().stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p))); + } + } + } + for (List<CapabilityDefinition> capabilities : originCapabilities.values()) { + List<CapabilityDefinition> filteredCapabilities = capabilities.stream() + .filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList()); + for (CapabilityDefinition cap : filteredCapabilities) { + Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(), + newPropertiesMap.get(cap.getName()), allDataTypes.left().value()); + if (updateRes.isRight()) { + log.debug("Failed to update capability properties of capability {} . Status is {}. ", + cap.getName(), updateRes.right().value()); + return Either.right(updateRes.right().value()); + } + } + } + } else { + originCapabilities = originResource.getCapabilities(); + } + instCapabilties.put(currentCompInstance, originCapabilities); + } + if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) + instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); + if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) + instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); + if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) + instAttributes.put(resourceInstanceId, originResource.getAttributes()); + if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { + ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, + originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value()); + if (addPropertiesValueToRiRes.getStatus() != 200) { + return Either.right(addPropertiesValueToRiRes); + } + } else { + ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, + originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value()); + if (addInputValueToRiRes.getStatus() != 200) { + return Either.right(addInputValueToRiRes); + } + } + } + + Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade + .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + if (addPropToInst.isRight()) { + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), + addPropToInst.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName); + return Either.right(responseFormat); + } + if (instInputs != null && !instInputs.isEmpty()) { + Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade + .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); + if (addInputToInst.isRight()) { + log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), + addInputToInst.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName); + return Either.right(responseFormat); + } + } + StorageOperationStatus addArtToInst = toscaOperationFacade + .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, + resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, + resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreComponentInstancesProperties(false); + parametersView.setIgnoreCapabilities(false); + parametersView.setIgnoreRequirements(false); + + Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + + return Either.right(responseFormat); + + } + + resource = eitherGetResource.left().value(); + + for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) { + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return Either.right(responseFormat); + } + + ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); + if (addRelationToRiRes.getStatus() != 200) { + return Either.right(addRelationToRiRes); + } + } + + addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + if (resource.getResourceType() == ResourceTypeEnum.CVFC) { + eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(), + uploadResInstancesMap); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + } + + log.debug("************* in create relations, getResource start"); + eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(eitherGetResource.left().value()); + } + + private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties, + Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) { + for (ComponentInstanceProperty property : properties) { + Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property, + newProperties.get(property.getName()), allDataTypes); + if (updateRes.isRight()) { + log.debug("Failed to update capability property {} . Status is {}. ", property.getName(), + updateRes.right().value()); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value()))); + } + } + return Either.left(true); + } + + private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property, + UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) { + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + property.setValue(value); + return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes); + } + + private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) { + Either<Resource, StorageOperationStatus> updateRes = null; + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>(); + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>(); + StorageOperationStatus status = toscaOperationFacade + .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + if (updateRes == null) { + fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, + updatedInstCapabilities, updatedInstRequirements); + status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, + resource.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + } + if (updateRes == null) { + updateRes = Either.left(resource); + } + return updateRes; + } + + private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) { + + componentInstances.stream().forEach(i -> { + fillUpdatedInstCapabilities(updatedInstCapabilities, i, + uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); + fillUpdatedInstRequirements(updatedInstRequirements, i, + uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); + }); + } + + private void fillUpdatedInstRequirements( + Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, + ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) { + Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>(); + Set<String> updatedReqNames = new HashSet<>(); + if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) { + for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) { + updatedRequirements.put(requirements.getKey(), + requirements.getValue().stream() + .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) + && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) + .map(r -> { + r.setParentName(r.getName()); + r.setName(requirementsNamesToUpdate.get(r.getName())); + updatedReqNames.add(r.getName()); + return r; + }).collect(Collectors.toList())); + } + } + if (MapUtils.isNotEmpty(updatedRequirements)) { + updatedInstRequirements.put(instance, updatedRequirements); + } + } + + private void fillUpdatedInstCapabilities( + Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, + ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) { + Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>(); + Set<String> updatedCapNames = new HashSet<>(); + if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) { + for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) { + updatedCapabilities.put(requirements.getKey(), + requirements.getValue().stream() + .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) + && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) + .map(c -> { + c.setParentName(c.getName()); + c.setName(capabilitiesNamesToUpdate.get(c.getName())); + updatedCapNames.add(c.getName()); + return c; + }).collect(Collectors.toList())); + } + } + if (MapUtils.isNotEmpty(updatedCapabilities)) { + updatedInstCapabilties.put(instance, updatedCapabilities); + } + } + + private ResponseFormat addRelationToRI(String yamlName, Resource resource, + UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) { + List<ComponentInstance> componentInstancesList = resource.getComponentInstances(); + + UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue; + + ComponentInstance currentCompInstance = null; + + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return responseFormat; + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + + Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements(); + + if (regMap != null) { + Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator(); + + while (nodesRegValue.hasNext()) { + Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next(); + + List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue(); + for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { + log.debug("Going to create relation {}", uploadRegInfo.getName()); + String regName = uploadRegInfo.getName(); + RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); + regCapRelDef.setFromNode(resourceInstanceId); + log.debug("try to find available requirement {} ", regName); + Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, + yamlName, uploadComponentInstanceInfo, currentCompInstance, + uploadRegInfo.getCapabilityName()); + if (eitherReqStatus.isRight()) { + log.debug("failed to find available requirement {} status is {}", regName, + eitherReqStatus.right().value()); + return eitherReqStatus.right().value(); + } + + RequirementDefinition validReq = eitherReqStatus.left().value(); + List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef + .getRelationships(); + if (reqAndRelationshipPairList == null) + reqAndRelationshipPairList = new ArrayList<>(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + reqAndRelationshipPair.setRequirement(regName); + reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); + reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(validReq.getCapability()); + reqAndRelationshipPair.setRelationships(relationship); + + ComponentInstance currentCapCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName().equals(uploadRegInfo.getNode())) { + currentCapCompInstance = compInstance; + break; + } + } + + if (currentCapCompInstance == null) { + log.debug("The component instance with name {} not found on resource {} ", + uploadRegInfo.getNode(), resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadRegInfo.getNode() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); + log.debug("try to find aviable Capability req name is {} ", validReq.getName()); + CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, + currentCapCompInstance, uploadRegInfo); + if (aviableCapForRel == null) { + log.debug("aviable capability was not found. req name is {} component instance is {}", + validReq.getName(), currentCapCompInstance.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "aviable capability was not found. req name is " + validReq.getName() + + " component instance is " + currentCapCompInstance.getUniqueId(), + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); + reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); + reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(reqAndRelationshipPair); + reqAndRelationshipPairList.add(capReqRel); + regCapRelDef.setRelationships(reqAndRelationshipPairList); + relations.add(regCapRelDef); + } + } + } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); + return responseFormat; + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, + Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, + Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) { + Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); + if (propMap != null && propMap.size() > 0) { + Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>(); + + List<InputDefinition> listFromMap = originResource.getInputs(); + if (listFromMap == null || listFromMap.isEmpty()) { + log.debug("failed to find properties "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + return responseFormat; + } + for (InputDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + List<ComponentInstanceInput> instPropList = new ArrayList<>(); + for (List<UploadPropInfo> propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + propName); + return responseFormat; + } + InputDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceInput property = null; + + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + curPropertyDef.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + String innerType = null; + property = new ComponentInstanceInput(curPropertyDef, value, null); + + Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, + value, isValidate, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + return componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); + } + + property.setValue(validatevalueEiter.left().value()); + + if (getInputs != null && !getInputs.isEmpty()) { + List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List<InputDefinition> inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", + property, currentCompInstance.getUniqueId()); + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + + Optional<InputDefinition> optional = inputs.stream() + .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) + .findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInputIndex.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + } + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (InputDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceInput(value)); + } + } + instInputs.put(currentCompInstance.getUniqueId(), instPropList); + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, + Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, + Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) { + + Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties(); + Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>(); + + List<PropertyDefinition> listFromMap = originResource.getProperties(); + if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { + log.debug("failed to find properties "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + return responseFormat; + } + if (listFromMap == null || listFromMap.isEmpty()) { + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + for (PropertyDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + List<ComponentInstanceProperty> instPropList = new ArrayList<>(); + if (propMap != null && propMap.size() > 0) { + for (List<UploadPropInfo> propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + propName); + return responseFormat; + } + PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceProperty property = null; + + String value = null; + List<GetInputValueDataDefinition> getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + curPropertyDef.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + String innerType = null; + property = new ComponentInstanceProperty(curPropertyDef, value, null); + + Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, + value, isValidate, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + return componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); + } + + property.setValue(validatevalueEiter.left().value()); + + if (getInputs != null && !getInputs.isEmpty()) { + List<GetInputValueDataDefinition> getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List<InputDefinition> inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", + property, currentCompInstance.getUniqueId()); + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + + Optional<InputDefinition> optional = inputs.stream() + .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) + .findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInputIndex.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + + } + + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (PropertyDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceProperty(value)); + } + } + instProperties.put(currentCompInstance.getUniqueId(), instPropList); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + // US740820 Relate RIs according to capability name + private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + if (null == uploadReqInfo.getCapabilityName() + || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get + // by + // capability + // type + return findAviableCapability(validReq, currentCapCompInstance); + } + return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); + } + + private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + CapabilityDefinition cap = null; + Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); + if (!capMap.containsKey(validReq.getCapability())) { + return null; + } + Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream() + .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); + if (!capByName.isPresent()) { + return null; + } + cap = capByName.get(); + + if (cap.getMaxOccurrences() != null + && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + + } + + } + return cap; + } + + private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance) { + CapabilityDefinition aviableCapForRel = null; + Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities(); + if (capMap.containsKey(validReq.getCapability())) { + List<CapabilityDefinition> capList = capMap.get(validReq.getCapability()); + + for (CapabilityDefinition cap : capList) { + if (cap.getMaxOccurrences() != null + && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = cap.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + aviableCapForRel = cap; + break; + } else { + continue; + } + } else { + aviableCapForRel = cap; + break; + } + } + } + return aviableCapForRel; + } + + private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, + String capName) { + Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements(); + List<RequirementDefinition> list = comInstRegDefMap.get(capName); + RequirementDefinition validRegDef = null; + if (list == null) { + for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) { + for (RequirementDefinition reqDef : entry.getValue()) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null + && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + + } + } + if (validRegDef != null) { + break; + } + } + } else { + for (RequirementDefinition reqDef : list) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null + && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + } + } + } + if (validRegDef == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + return Either.left(validRegDef); + } + + @SuppressWarnings("unchecked") + public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, + String resourceYml, Map<String, String> createdNodesToscaResourceNames, + Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) { + + Map<String, Object> mappedToscaTemplate; + if (nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); + } else { + try { + // DE154502 Fail if duplicate key found in file + mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml); + + } catch (ParserException e) { + log.error("Failed to load yaml file {}", yamlFileName, e); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, + yamlFileName, e.getMessage()); + return Either.right(responseFormat); + } + } + Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); + if (toscaElementEither.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + return Either.right(responseFormat); + } + + Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, + mappedToscaTemplate, resource); + if (createInputsEither.isRight()) { + ResponseFormat responseFormat = createInputsEither.right().value(); + return Either.right(responseFormat); + } + + Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml( + yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames); + if (uploadResInstancesEither.isRight()) { + ResponseFormat responseFormat = uploadResInstancesEither.right().value(); + return Either.right(responseFormat); + } + + Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, + mappedToscaTemplate, resource); + if (createGroupsFromYaml.isRight()) { + ResponseFormat responseFormat = createGroupsFromYaml.right().value(); + return Either.right(responseFormat); + } + + ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo(); + parsedToscaYamlInfo.setInputs(createInputsEither.left().value()); + parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value()); + parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value()); + + return Either.left(parsedToscaYamlInfo); + } + + private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, + Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock, + Map<String, Resource> nodeNamespaceMap) { + + Either<Resource, ResponseFormat> eitherResource = null; + log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); + if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + + return Either.right(responseFormat); + + } + Map<String, Resource> existingnodeTypeMap = new HashMap<>(); + if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) { + nodeNamespaceMap.entrySet().stream() + .forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue())); + } + + Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet() + .iterator(); + Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>(); + while (nodesInfoValue.hasNext()) { + log.debug("*************Going to create resource instances {}", yamlName); + Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next(); + UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); + + // updating type if the type is node type name - we need to take the + // updated name + log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + uploadComponentInstanceInfo + .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); + } + + eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, + existingnodeTypeMap); + if (eitherResource.isRight()) { + return eitherResource; + } + Resource refResource = eitherResource.left().value(); + + ComponentInstance componentInstance = new ComponentInstance(); + + componentInstance.setComponentUid(refResource.getUniqueId()); + + ComponentTypeEnum containerComponentType = resource.getComponentType(); + NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); + + if (containerNodeType.equals(NodeTypeEnum.Resource) + && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) + && MapUtils.isNotEmpty(refResource.getCapabilities())) { + setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); + Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities( + refResource.getUniqueId(), refResource.getCapabilities(), + uploadComponentInstanceInfo.getCapabilities()); + if (getValidComponentInstanceCapabilitiesRes.isRight()) { + return Either.right(getValidComponentInstanceCapabilitiesRes.right().value()); + } else { + componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value()); + } + } + if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { + log.debug( + "createResourceInstances - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); + componentInstance.setName(uploadComponentInstanceInfo.getName()); + componentInstance.setIcon(origResource.getIcon()); + + resourcesInstancesMap.put(componentInstance, origResource); + + } + if (MapUtils.isNotEmpty(resourcesInstancesMap)) { + + StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, + resourcesInstancesMap, false); + if (status != null && status != StorageOperationStatus.OK) { + log.debug("Failed to add component instances to container component {}", resource.getName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(status)); + eitherResource = Either.right(responseFormat); + return eitherResource; + } + + } + + log.debug("*************Going to get resource {}", resource.getUniqueId()); + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreInputs(false); // inputs are read when creating + // property values on instances + Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + log.debug("*************finished to get resource {}", resource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + return Either.right(responseFormat); + + } + + if (eitherGerResource.left().value().getComponentInstances() == null + || eitherGerResource.left().value().getComponentInstances().isEmpty()) { + + log.debug("Error when create resource inctanse from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance().logBeDaoSystemError( + "Error when create resource inctanse from csar. ComponentInstances list empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + return Either.right(responseFormat); + + } + + return Either.left(eitherGerResource.left().value()); + } + + private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, + Map<String, List<UploadCapInfo>> uploadedCapabilities) { + for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) { + if (originCapabilities.containsKey(currEntry.getKey())) { + currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); + } + } + for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) { + capabilities.getValue().stream().forEach(cap -> { + if (uploadedCapabilities.containsKey(cap.getName())) { + uploadedCapabilities.get(cap.getName()).stream().forEach(c -> { + c.setName(cap.getName()); + c.setType(cap.getType()); + }); + } + ; + }); + } + + } + + private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) { + log.debug( + "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + Resource refResource = null; + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); + } else { + Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade + .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); + if (findResourceEither.isRight()) { + log.debug( + "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + return Either.right(responseFormat); + } + refResource = findResourceEither.left().value(); + nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); + } + String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); + if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", + refResource.getName(), componentState); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, + refResource.getComponentType().getValue(), refResource.getName(), componentState); + return Either.right(responseFormat); + } + + if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { + log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + return Either.left(refResource); + } + + private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml( + String yamlFileName, Map<String, Object> toscaJson, Resource resource, + Map<String, String> createdNodesToscaResourceNames) { + Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>(); + Map<String, Object> substitutionMappings = null; + Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances); + Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES); + Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS); + if (eitherSubstitutionMappings.isLeft()) { + substitutionMappings = eitherSubstitutionMappings.left().value(); + } + if (eitherNodesTemlates.isLeft()) { + Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value(); + + Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry<String, Object> nodeNameValue = nodesNameValue.next(); + Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo( + nodeNameValue, substitutionMappings, createdNodesToscaResourceNames); + if (eitherNode.isRight()) { + log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), + resource.getName()); + return Either.right(eitherNode.right().value()); + } else { + UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value(); + moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo); + } + + } + + } + if (moduleComponentInstances.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlFileName); + return Either.right(responseFormat); + } + + return result; + } + + @SuppressWarnings("unchecked") + private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo( + Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, + Map<String, String> createdNodesToscaResourceNames) { + + UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo(); + Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo); + nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey()); + try { + if (nodeTemplateJsonEntry.getValue() instanceof String) { + String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue(); + nodeTemplateInfo.setType(nodeTemplateJsonString); + } else if (nodeTemplateJsonEntry.getValue() instanceof Map) { + Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue(); + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String toscaResourceType = (String) nodeTemplateJsonMap + .get(ToscaTagNamesEnum.TYPE.getElementName()); + if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) { + toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType); + } + nodeTemplateInfo.setType(toscaResourceType); + } + + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { + Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml( + nodeTemplateInfo, nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + nodeTemplateInfo.setRequirements(regResponse.left().value()); + } + } + + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { + Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml( + nodeTemplateInfo, nodeTemplateJsonMap); + if (eitherCapRes.isRight()) + return Either.right(eitherCapRes.right().value()); + if (eitherCapRes.left().value().size() > 0) { + nodeTemplateInfo.setCapabilities(eitherCapRes.left().value()); + } + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml( + nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + nodeTemplateInfo.setProperties(regResponse.left().value()); + } + } + if (substitutionMappings != null) { + if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { + Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate( + nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings + .get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); + if (getCapNamesToUpdateRes.isRight()) + return Either.right(getCapNamesToUpdateRes.right().value()); + if (getCapNamesToUpdateRes.left().value().size() > 0) { + nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value()); + } + } + if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { + Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate( + nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings + .get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); + if (getReqNamesToUpdateRes.isRight()) + return Either.right(getReqNamesToUpdateRes.right().value()); + if (getReqNamesToUpdateRes.left().value().size() > 0) { + nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value()); + } + } + } + } else { + + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); + log.debug("error when creating capability, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, + Map<String, List<String>> elements) { + Either<Map<String, String>, ResponseFormat> response; + try { + Map<String, String> namesToUpdate = elements.entrySet().stream() + .filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())) + .collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey())); + response = Either.left(namesToUpdate); + } catch (Exception e) { + log.debug("The exception occurred upon adding names to update for instance {}: ", nodeTemplateInfo.getName(), e); + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return response; + } + + @SuppressWarnings("unchecked") + private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml( + Map<String, Object> nodeTemplateJsonMap) { + Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>(); + Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp); + Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES); + if (toscaProperties.isLeft()) { + Map<String, Object> jsonProperties = toscaProperties.left().value(); + for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) { + // Property + String propName = jsonPropObj.getKey(); + Object propValue = jsonPropObj.getValue(); + + if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(TOKEN_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(CONCAT_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(GET_ATTRIBUTE_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + UploadPropInfo propertyDef = new UploadPropInfo(); + propertyDef.setValue(propValue); + propertyDef.setName(propName); + if (propValue instanceof Map) { + if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + propertyDef.setType(((Map<String, Object>) propValue) + .get(ToscaTagNamesEnum.TYPE.getElementName()).toString()); + } + + if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()) + || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()) + .contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef); + } + + if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + propertyDef.setDescription(((Map<String, Object>) propValue) + .get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString()); + } + if (((Map<String, Object>) propValue) + .containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) { + propertyDef.setValue(((Map<String, Object>) propValue) + .get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())); + } + if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) { + propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue) + .get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString())); + } else { + propertyDef.setValue(propValue); + } + } else if (propValue instanceof List) { + List<Object> propValueList = (List<Object>) propValue; + + createInputPropList(propertyDef, propValueList); + propertyDef.setValue(propValue); + } + + if (moduleProp.containsKey(propName)) { + moduleProp.get(propName).add(propertyDef); + } else { + List<UploadPropInfo> list = new ArrayList<UploadPropInfo>(); + list.add(propertyDef); + moduleProp.put(propName, list); + } + } + } + return response; + } + + @SuppressWarnings("unchecked") + private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) { + for (Object objValue : propValueList) { + + if (objValue instanceof Map) { + Map<String, Object> objMap = (Map<String, Object>) objValue; + if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) + createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef); + else { + Set<String> keys = objMap.keySet(); + for (String key : keys) { + Object value = objMap.get(key); + if (value instanceof Map) { + createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef); + + } else if (value instanceof List) { + List<Object> propSubValueList = (List<Object>) value; + + createInputPropList(propertyDef, propSubValueList); + } + + } + } + + } else if (objValue instanceof List) { + List<Object> propSubValueList = (List<Object>) objValue; + + createInputPropList(propertyDef, propSubValueList); + + } + + } + } + + @SuppressWarnings("unchecked") + private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, + UploadPropInfo propertyDef) { + + if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName()); + GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); + List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input(); + if (getInputs == null) { + getInputs = new ArrayList<GetInputValueDataDefinition>(); + } + if (getInput instanceof String) { + + getInputInfo.setInputName((String) getInput); + getInputInfo.setPropName(propName); + + } else if (getInput instanceof List) { + List<Object> getInputList = (List<Object>) getInput; + getInputInfo.setPropName(propName); + getInputInfo.setInputName((String) getInputList.get(0)); + if (getInputList.size() > 1) { + Object indexObj = getInputList.get(1); + if (indexObj instanceof Integer) { + getInputInfo.setIndexValue((Integer) indexObj); + } else if (indexObj instanceof Float) { + int index = ((Float) indexObj).intValue(); + getInputInfo.setIndexValue(index); + } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj) + .containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + Object index = ((Map<String, Object>) indexObj) + .get(ToscaTagNamesEnum.GET_INPUT.getElementName()); + GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); + getInputInfoIndex.setInputName((String) index); + getInputInfoIndex.setPropName(propName); + getInputInfo.setGetInputIndex(getInputInfoIndex); + } + getInputInfo.setList(true); + } + + } + getInputs.add(getInputInfo); + propertyDef.setGet_input(getInputs); + propertyDef.setValue(propValue); + } else { + Set<String> keys = propValue.keySet(); + for (String key : keys) { + Object value = propValue.get(key); + if (value instanceof Map) { + createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef); + + } else if (value instanceof List) { + List<Object> valueList = (List<Object>) value; + for (Object o : valueList) { + if (o instanceof Map) { + createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef); + + } + } + + } + + } + + } + } + + + private boolean valueContainsPattern(Pattern pattern, Object propValue) { + + log.debug("valueContainsToken value is {}", propValue); + boolean result = false; + if (propValue != null) { + log.trace("valueContainspattern value is {}", propValue.getClass()); + Matcher matcher = pattern.matcher(propValue.toString()); + result = matcher.find(); + } + + return result; + + } + + @SuppressWarnings("unchecked") + private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml( + UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) { + Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>(); + Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements); + Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); + + if (requirementsListRes.isLeft()) { + for (Object jsonReqObj : requirementsListRes.left().value()) { + String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next(); + Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName); + Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, + moduleRequirements, reqJson, reqName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } else { + Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); + if (requirementsMapRes.isLeft()) { + for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) { + String reqName = entry.getKey(); + Object reqJson = entry.getValue(); + Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, + moduleRequirements, reqJson, reqName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } + } + return response; + } + + private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo, + Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) { + + Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson); + if (eitherRequirement.isRight()) { + log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo); + return Either.right(eitherRequirement.right().value()); + } else { + UploadReqInfo requirementDef = eitherRequirement.left().value(); + requirementDef.setName(requirementName); + if (moduleRequirements.containsKey(requirementName)) { + moduleRequirements.get(requirementName).add(requirementDef); + } else { + List<UploadReqInfo> list = new ArrayList<UploadReqInfo>(); + list.add(requirementDef); + moduleRequirements.put(requirementName, list); + } + } + return Either.left(eitherRequirement.left().value()); + } + + @SuppressWarnings("unchecked") + private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml( + UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) { + Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>(); + Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap); + Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); + if (capabilitiesListRes.isLeft()) { + for (Object jsonCapObj : capabilitiesListRes.left().value()) { + String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next(); + Object capJson = ((Map<String, Object>) jsonCapObj).get(key); + Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, + capJson, key); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } else { + Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); + if (capabilitiesMapRes.isLeft()) { + for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) { + String capName = entry.getKey(); + Object capJson = entry.getValue(); + Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, + moduleCap, capJson, capName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } + } + return response; + } + + private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, + Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) { + + Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson); + if (eitherCap.isRight()) { + log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo); + return Either.right(eitherCap.right().value()); + } else { + UploadCapInfo capabilityDef = eitherCap.left().value(); + capabilityDef.setKey(key); + if (moduleCap.containsKey(key)) { + moduleCap.get(key).add(capabilityDef); + } else { + List<UploadCapInfo> list = new ArrayList<UploadCapInfo>(); + list.add(capabilityDef); + moduleCap.put(key, list); + } + } + return Either.left(eitherCap.left().value()); + } + + @SuppressWarnings("unchecked") + private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) { + UploadCapInfo capTemplateInfo = new UploadCapInfo(); + Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo); + + if (capObject instanceof String) { + String nodeTemplateJsonString = (String) capObject; + capTemplateInfo.setNode(nodeTemplateJsonString); + } else if (capObject instanceof Map) { + Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject; + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { + Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES); + if (validSourceTypesRes.isLeft()) { + capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream() + .map(o -> o.toString()).collect(Collectors.toList())); + } + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml( + nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (!regResponse.left().value().isEmpty()) { + List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>(); + regResponse.left().value().values().forEach(list -> properties.addAll(list)); + if (!properties.isEmpty()) + capTemplateInfo.setProperties(properties); + } + } + } + return result; + } + + @SuppressWarnings("unchecked") + private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) { + + UploadReqInfo regTemplateInfo = new UploadReqInfo(); + Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo); + + if (regObject instanceof String) { + String nodeTemplateJsonString = (String) regObject; + regTemplateInfo.setNode(nodeTemplateJsonString); + } else if (regObject instanceof Map) { + Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject; + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + // US740820 Relate RIs according to capability name + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { + regTemplateInfo.setCapabilityName( + (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); + } + } + return result; + } + + public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, + boolean forceCertificationAllowed) { + + Either<Resource, ResponseFormat> result = null; + try { + if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed + && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) { + result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); + if (result.isRight()) { + return result; + } + resource = result.left().value(); + } + if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts( + resource, user, false, inTransaction, needLock); + result = eitherPopulated.isLeft() ? Either.left(resource) + : Either.right(eitherPopulated.right().value()); + return result; + } + return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); + } catch (Exception e) { + log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + + private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, + LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock); + if (result.isLeft()) { + result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, + lifecycleChangeInfo, inTransaction, needLock); + } + if (result.isLeft()) { + result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, + lifecycleChangeInfo, inTransaction, needLock); + } + return result; + } + + private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, + needLock); + } + + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport( + Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, + CsarInfo csarInfo, String nodeName, boolean isNested) { + + // check if resource already exist + Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade + .getLatestByName(resource.getName()); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null; + + // create + if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + + Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(resource.getToscaResourceName()); + if (csarInfo != null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() + && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), + csarInfo.getVfResourceName(), nodeName).getRight()); + // update + if (latestByToscaName.isLeft()) { + log.debug("validate derived before update"); + Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate( + latestByToscaName.left().value(), resource, + ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion())); + if (eitherValidation.isRight()) { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } else { + result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, + isNormative, needLock, isNested); + } + } + } + if (result == null && latestByToscaName.isRight() + && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } else if (result == null) { + StorageOperationStatus status = latestByName.right().value(); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + log.debug("resource already exist {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + result = Either.right(responseFormat); + } + + } + + // update + else if (latestByName.isLeft()) { + result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, + isNested); + } + + // error + else { + StorageOperationStatus status = latestByName.right().value(); + log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + result = Either.right(responseFormat); + } + return result; + + } + + private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, + User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { + log.debug("resource with name {} does not exist. create new resource", resource.getName()); + Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, + AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); + if (response.isRight()) { + return Either.right(response.right().value()); + } + Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, + AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction); + if (createResponse.isRight()) { + return Either.right(createResponse.right().value()); + } else { + ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), + ActionStatus.CREATED); + ASDCKpiApi.countImportResourcesKPI(); + return Either.left(resourcePair); + + } + } + + public boolean isResourceExist(String resourceName) { + Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName); + return latestByName.isLeft(); + } + + private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport( + Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, + boolean isNested) { + String lockedResourceId = oldResource.getUniqueId(); + log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, + oldResource.getVersion(), oldResource.getLifecycleState()); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null; + try { + if (needLock) { + Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, + "Update Resource by Import"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + } + + Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, + inTransaction, false); + if (prepareResourceForUpdate.isRight()) { + ResponseFormat responseFormat = prepareResourceForUpdate.right().value(); + log.info("resource {} cannot be updated. reason={}", lockedResourceId, + responseFormat.getFormattedMessage()); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(oldResource.getLifecycleState().name()) + .version(oldResource.getVersion()) + .build()); + result = Either.right(prepareResourceForUpdate.right().value()); + return result; + } + oldResource = prepareResourceForUpdate.left().value(); + + mergeOldResourceMetadataWithNew(oldResource, newResource); + + Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, + newResource, inTransaction, isNested); + if (validateFieldsResponse.isRight()) { + result = Either.right(validateFieldsResponse.right().value()); + return result; + } + + validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, + AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + if (validateFieldsResponse.isRight()) { + return Either.right(validateFieldsResponse.right().value()); + } + + // contact info normalization + newResource.setContactId(newResource.getContactId().toLowerCase()); + // non-updatable fields + newResource.setCreatorUserId(user.getUserId()); + newResource.setCreatorFullName(user.getFullName()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setLastUpdaterFullName(user.getFullName()); + newResource.setUniqueId(oldResource.getUniqueId()); + newResource.setVersion(oldResource.getVersion()); + newResource.setInvariantUUID(oldResource.getInvariantUUID()); + newResource.setLifecycleState(oldResource.getLifecycleState()); + newResource.setUUID(oldResource.getUUID()); + newResource.setNormalizedName(oldResource.getNormalizedName()); + newResource.setSystemName(oldResource.getSystemName()); + if (oldResource.getCsarUUID() != null) { + newResource.setCsarUUID(oldResource.getCsarUUID()); + } + if (oldResource.getImportedToscaChecksum() != null) { + newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); + } + newResource.setAbstract(oldResource.isAbstract()); + + if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) { + newResource.setDerivedFrom(oldResource.getDerivedFrom()); + } + if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) { + newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); + } + if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) { + newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); + } + // TODO rhalili: handle artifacts here (delete from old resource and + // add for new) + // TODO rbetzer: remove after migration - in case of resources + // created without tosca artifacts - add the placeholders + if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { + setToscaArtifactsPlaceHolders(newResource, user); + } + Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade + .overrideComponent(newResource, oldResource); + + if (overrideResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE); + + result = Either.right(responseFormat); + return result; + } + + log.debug("Resource updated successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build()); + + + ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), + ActionStatus.OK); + result = Either.left(resourcePair); + return result; + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } else if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + if (needLock == true) { + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + } + + } + + /** + * Merge old resource with new. Keep old category and vendor name without + * change + * + * @param oldResource + * @param newResource + */ + private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { + + // keep old category and vendor name without change + // merge the rest of the resource metadata + if (newResource.getTags() == null || newResource.getTags().isEmpty()) { + newResource.setTags(oldResource.getTags()); + } + + if (newResource.getDescription() == null) { + newResource.setDescription(oldResource.getDescription()); + } + + if (newResource.getVendorRelease() == null) { + newResource.setVendorRelease(oldResource.getVendorRelease()); + } + + if (newResource.getResourceVendorModelNumber() == null) { + newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); + } + + if (newResource.getContactId() == null) { + newResource.setContactId(oldResource.getContactId()); + } + + newResource.setCategories(oldResource.getCategories()); + if (newResource.getVendorName() == null) { + newResource.setVendorName(oldResource.getVendorName()); + } + } + + private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, + boolean inTransaction, boolean needLock) { + + Either<Resource, ResponseFormat> result = Either.left(latestResource); + // check if user can edit resource + if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) { + // checkout + Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState( + latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock); + result = changeState; + } + + return result; + } + + public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, + AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { + + Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, + actionEnum, inTransaction); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, + inTransaction); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + eitherValidation = validateResourceType(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setContactId(resource.getContactId().toLowerCase()); + if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { + String resourceSystemName; + if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) { + resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); + } else { + resourceSystemName = resource.getSystemName(); + } + resource.setToscaResourceName(CommonBeUtils + .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); + } + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + // TODO + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + resource.setInvariantUUID(invariantUUID); + + return Either.left(resource); + } + + private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getResourceType() == null) { + log.debug("Invalid resource type for resource"); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } + + private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { + log.debug("validate interface lifecycle Types Exist"); + Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator(); + while (intItr.hasNext() && eitherResult.isLeft()) { + InterfaceDefinition interfaceDefinition = intItr.next(); + String intType = interfaceDefinition.getUniqueId(); + Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation + .getInterface(intType); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateLifecycleTypesCreate", "Interface", intType); + log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", + intType, resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); + log.debug("request to data model failed with error: {}", + eitherCapTypeFound.right().value().name()); + } + + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + + } + } + return eitherResult; + } + + private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + boolean inTransaction) { + + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { + log.debug("validate capability Types Exist - capabilities section"); + + for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) { + + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, + eitherResult, typeEntry, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right().value()); + } + } + } + + if (resource.getRequirements() != null && resource.getRequirements().size() > 0) { + log.debug("validate capability Types Exist - requirements section"); + for (String type : resource.getRequirements().keySet()) { + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, + resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right().value()); + } + } + } + + return eitherResult; + } + + // @param typeObject- the object to which the validation is done + private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, + AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type, + boolean inTransaction) { + Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(type, inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateCapabilityTypesCreate", "Capability Type", type); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, + resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); + } + log.debug("Trying to get capability type {} failed with error: {}", type, + eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = null; + if (type != null) + errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); + else + errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, + validationObjects); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } + + private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry, + boolean inTransaction) { + Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(typeEntry.getKey(), inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey()); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", + typeEntry.getKey(), resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); + } + log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), + eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, + typeEntry.getKey()); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); + if (capabilityTypeDefinition.getProperties() != null) { + for (CapabilityDefinition capDef : typeEntry.getValue()) { + List<ComponentInstanceProperty> properties = capDef.getProperties(); + if (properties == null || properties.isEmpty()) { + properties = new ArrayList<ComponentInstanceProperty>(); + for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); + properties.add(newProp); + } + } else { + for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) { + PropertyDefinition porpFromDef = prop.getValue(); + List<ComponentInstanceProperty> propsToAdd = new ArrayList<>(); + for (ComponentInstanceProperty cip : properties) { + if (!cip.getName().equals(porpFromDef.getName())) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); + propsToAdd.add(newProp); + } + } + if (!propsToAdd.isEmpty()) { + properties.addAll(propsToAdd); + } + } + } + capDef.setProperties(properties); + } + } + return eitherResult; + } + + public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, + AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) { + // create resource + + // lock new resource name in order to avoid creation resource with same + // name + if (inTransaction == false) { + Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, + "Create Resource"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + if (resource.deriveFromGeneric()) { + Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource); + if (genericResourceEither.isRight()) + return genericResourceEither; + } + + Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, + inTransaction); + if (respStatus.isLeft()) { + componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, + respStatus.left().value(), actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + } else + componentsUtils.auditResource(respStatus.right().value(), user, resource, actionEnum); + return respStatus; + + } finally { + if (inTransaction == false) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + } + + private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, user, persistedResource, actionEnum); + } + + private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, + boolean isNormative, boolean inTransaction) { + // validate resource name uniqueness + log.debug("validate resource name"); + Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists( + resource.getName(), resource.getResourceType(), resource.getComponentType()); + if (eitherValidation.isRight()) { + log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), + eitherValidation.right().value()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); + return Either.right(errorResponse); + } + if (eitherValidation.left().value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + return Either.right(errorResponse); + } + + log.debug("send resource {} to dao for create", resource.getName()); + + createArtifactsPlaceHolderData(resource, user); + + // + + // enrich object + if (!isNormative) { + log.debug("enrich resource with creator, version and state"); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setVersion(INITIAL_VERSION); + resource.setHighestVersion(true); + if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) + resource.setAbstract(false); + } + + Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade + .createToscaComponent(resource); + if (createToscaElement.isLeft()) { + return Either.left(createToscaElement.left().value()); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource); + + return Either.right(responseFormat); + } + + private void createArtifactsPlaceHolderData(Resource resource, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + + setInformationalArtifactsPlaceHolder(resource, user); + setDeploymentArtifactsPlaceHolder(resource, user); + setToscaArtifactsPlaceHolders(resource, user); + } + + @SuppressWarnings("unchecked") + @Override + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + Resource resource = (Resource) component; + Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<String, ArtifactDefinition>(); + } + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration().getDeploymentResourceArtifacts(); + if (deploymentResourceArtifacts != null) { + Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator(); + while (iterator.hasNext()) { + Entry<String, Object> currEntry = iterator.next(); + boolean shouldCreateArtifact = true; + Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue(); + Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); + if (object != null) { + List<String> artifactTypes = (List<String>) object; + if (!artifactTypes.contains(resource.getResourceType().name())) { + shouldCreateArtifact = false; + continue; + } + } else { + log.info("resource types for artifact placeholder {} were not defined. default is all resources", + currEntry.getKey()); + } + if (shouldCreateArtifact) { + if (artifactsBusinessLogic != null) { + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), + user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null + && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + } + } + resource.setDeploymentArtifacts(artifactMap); + } + + @SuppressWarnings("unchecked") + private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { + Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<String, ArtifactDefinition>(); + } + String resourceUniqueId = resource.getUniqueId(); + List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludeResourceCategory(); + List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludeResourceType(); + Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration().getInformationalResourceArtifacts(); + List<CategoryDefinition> categories = resource.getCategories(); + boolean isCreateArtifact = true; + if (exludeResourceCategory != null) { + String category = categories.get(0).getName(); + for (String exlude : exludeResourceCategory) { + if (exlude.equalsIgnoreCase(category)) { + isCreateArtifact = false; + break; + } + } + + } + if (isCreateArtifact && exludeResourceType != null) { + String resourceType = resource.getResourceType().name(); + for (String type : exludeResourceType) { + if (type.equalsIgnoreCase(resourceType)) { + isCreateArtifact = false; + break; + } + } + + } + + if (informationalResourceArtifacts != null && isCreateArtifact) { + Set<String> keys = informationalResourceArtifacts.keySet(); + for (String informationalResourceArtifactName : keys) { + Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts + .get(informationalResourceArtifactName); + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, + ArtifactGroupTypeEnum.INFORMATIONAL); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + } + } + resource.setArtifacts(artifactMap); + } + + /** + * deleteResource + * + * @param resourceId + * @param user + * @return + */ + public ResponseFormat deleteResource(String resourceId, User user) { + ResponseFormat responseFormat; + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + + Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {}", resourceId); + return componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); + } + + Resource resource = resourceStatus.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + + result = markComponentToDelete(resource); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + + Resource resource = null; + StorageOperationStatus result = StorageOperationStatus.OK; + try { + + Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {} version {}", resourceName, version); + return componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); + } + + resource = resourceStatus.left().value(); + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + if (resource != null) { + Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, + "Delete Resource"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + try { + result = markComponentToDelete(resource); + if (!result.equals(StorageOperationStatus.OK)) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + return responseFormat; + } + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + return responseFormat; + } + + public Either<Resource, ResponseFormat> getResource(String resourceId, User user) { + + if (user != null) { + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + } + + Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId); + if (storageStatus.isRight()) { + log.debug("failed to get resource by id {}", resourceId); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId)); + } + if (!(storageStatus.left().value() instanceof Resource)) { + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); + } + return Either.left(storageStatus.left().value()); + + } + + public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, + String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); + if (getResource.isRight()) { + log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); + } + return Either.left(getResource.left().value()); + } + + /** + * updateResourceMetadata + * + * @param user - modifier data (userId) + * @param inTransaction TODO + * @param resourceIdToUpdate - the resource identifier + * @param newResource + * @return Either<Resource, responseFormat> + */ + public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, + Resource currentResource, User user, boolean inTransaction) { + + Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("Get resource with id {}", resourceIdToUpdate); + boolean needToUnlock = false; + boolean rollbackNeeded = true; + + try { + if (currentResource == null) { + Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade + .getToscaElement(resourceIdToUpdate); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + + currentResource = storageStatus.left().value(); + } + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // lock resource + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, + NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", + NodeTypeEnum.Resource.getName(), resourceIdToUpdate); + log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); + return Either.right(responseFormat); + } + + needToUnlock = true; + + // critical section starts here + // convert json to object + + // Update and updated resource must have a non-empty "derivedFrom" + // list + // This code is not called from import resources, because of root + // VF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(currentResource)) { + Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, + newResource, null); + if (derivedFromNotEmptyEither.isRight()) { + log.debug("for updated resource {}, derived from field is empty", newResource.getName()); + return Either.right(derivedFromNotEmptyEither.right().value()); + } + + derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null); + if (derivedFromNotEmptyEither.isRight()) { + log.debug("for current resource {}, derived from field is empty", currentResource.getName()); + return Either.right(derivedFromNotEmptyEither.right().value()); + } + } else { + newResource.setDerivedFrom(null); + } + + Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, + user, currentResource, false, true); + if (dataModelResponse.isRight()) { + log.debug("failed to update resource metadata!!!"); + rollbackNeeded = true; + return Either.right(dataModelResponse.right().value()); + } + + log.debug("Resource metadata updated successfully!!!"); + rollbackNeeded = false; + return Either.left(dataModelResponse.left().value()); + + } finally { + if (!inTransaction) { + if (rollbackNeeded) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + + if (needToUnlock) { + graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); + } + } + } + + private Either<List<GroupDefinition>, Boolean> updateComponentGroupName(String replacePattern, String with, + List<GroupDefinition> oldGroup) { + if (oldGroup == null || with == null || replacePattern == null || with.isEmpty() || replacePattern.isEmpty()) { + if (log.isInfoEnabled()) + log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}", + replacePattern, with, oldGroup == null ? null : " < size : " + oldGroup.size() + " >"); + return Either.right(false); + } + List<GroupDefinition> list = oldGroup.stream().map(group -> new GroupDefinition(group)) + .collect(Collectors.toList()); + for (GroupDefinition group : list) { + if (group != null && group.isSamePrefix(replacePattern)) { + String prefix = group.getName().substring(0, replacePattern.length()); + String newGroupName = group.getName().replaceFirst(prefix, with); + group.setName(newGroupName); + } + } + return Either.left(list); + } + + private boolean isComponentNameChanged(Resource newResource, Resource oldResource) { + if (newResource != null && oldResource != null) { // TODO - must protect + // all chain against + // null , use + // optional + String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + return !oldName.equals(futureName); + } + return false; + } + + private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, + User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { + // region -> Update groups name for newResource + if (isComponentNameChanged(currentResource, newResource)) { + String replacePattern = Optional.ofNullable( // get currentResource + // name from + // metadata + Optional.ofNullable( + Optional.ofNullable(currentResource).orElse(null).getComponentMetadataDefinition()) + .orElse(null).getMetadataDataDefinition()) + .orElse(null).getName(); + String with = Optional.ofNullable( // get newResource name from + // metadata + Optional.ofNullable(Optional.ofNullable(newResource).orElse(null).getComponentMetadataDefinition()) + .orElse(null).getMetadataDataDefinition()) + .orElse(null).getName(); + if (with != null && replacePattern != null) { + Either<List<GroupDefinition>, Boolean> result = updateComponentGroupName(replacePattern, with, + currentResource.getGroups()); + if (result.isLeft()) + newResource.setGroups((List<GroupDefinition>) result.left().value()); + } + } + // endregion + + Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, + newResource, inTransaction, false); + if (validateResourceFields.isRight()) { + return Either.right(validateResourceFields.right().value()); + } + // Setting last updater and uniqueId + newResource.setContactId(newResource.getContactId().toLowerCase()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setUniqueId(resourceIdToUpdate); + // Cannot set highest version through UI + newResource.setHighestVersion(currentResource.isHighestVersion()); + newResource.setCreationDate(currentResource.getCreationDate()); + + Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, + newResource, user.getUserId(), shouldLock, inTransaction); + + if (processUpdateOfDerivedFrom.isRight()) { + log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); + return Either.right(processUpdateOfDerivedFrom.right().value()); + } + + log.debug("send resource {} to dao for update", newResource.getUniqueId()); + if (newResource != null && newResource.getGroups() != null) { + for (GroupDefinition group : newResource.getGroups()) { + if (newResource.getComponentMetadataDefinition() != null + && newResource.getComponentMetadataDefinition().getMetadataDataDefinition() != null) + groupBusinessLogic.validateAndUpdateGroupMetadata( + newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), + user, ComponentTypeEnum.RESOURCE_INSTANCE, group, true, false); + } + } + Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .updateToscaElement(newResource); + + if (dataModelResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); + return Either.right(responseFormat); + } else if (dataModelResponse.left().value() == null) { + log.debug("No response from updateResource"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(dataModelResponse.left().value()); + } + + /** + * validateResourceFieldsBeforeCreate + * + * @param user - modifier data (userId) + * @return Either<Boolean, ErrorResponse> + */ + private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, + actionEnum); + if (componentsFieldsValidation.isRight()) { + return componentsFieldsValidation; + } + + + // validate category + log.debug("validate category"); + Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate vendor name & release & model number + log.debug("validate vendor name"); + eitherValidation = validateVendorName(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor release"); + eitherValidation = validateVendorReleaseName(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate resource vendor model number"); + eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + + // validate cost + log.debug("validate cost"); + eitherValidation = validateCost(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate licenseType + log.debug("validate licenseType"); + eitherValidation = validateLicenseType(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate template (derived from) + log.debug("validate derived from"); + if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + resource.setDerivedFrom(null); + } + eitherValidation = validateDerivedFromExist(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + // warn about non-updatable fields + checkComponentFieldsForOverrideAttempt(resource); + String currentCreatorFullName = resource.getCreatorFullName(); + if (currentCreatorFullName != null) { + log.warn("Resource Creator fullname is automatically set and cannot be updated"); + } + + String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); + if (currentLastUpdaterFullName != null) { + log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + + Long currentLastUpdateDate = resource.getLastUpdateDate(); + if (currentLastUpdateDate != null) { + log.warn("Resource last update date is automatically set and cannot be updated"); + } + + Boolean currentAbstract = resource.isAbstract(); + if (currentAbstract != null) { + log.warn("Resource abstract is automatically set and cannot be updated"); + } + + return Either.left(true); + } + + /** + * validateResourceFieldsBeforeUpdate + * + * @param currentResource - Resource object to validate + * @param isNested + * @return Either<Boolean, ErrorResponse> + */ + private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, + Resource updateInfoResource, boolean inTransaction, boolean isNested) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); + + // validate resource name + log.debug("validate resource name before update"); + Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, + hasBeenCertified, isNested); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate description + log.debug("validate description before update"); + eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate icon before update"); + eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate tags before update"); + eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor name before update"); + eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate resource vendor model number before update"); + eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor release before update"); + eitherValidation = validateVendorReleaseName(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate contact info before update"); + eitherValidation = validateContactId(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate derived before update"); + eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate category before update"); + eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // warn about non-updatable fields + String currentResourceVersion = currentResource.getVersion(); + String updatedResourceVersion = updateInfoResource.getVersion(); + + if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { + log.warn("Resource version is automatically set and cannot be updated"); + } + + String currentCreatorUserId = currentResource.getCreatorUserId(); + String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); + + if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { + log.warn("Resource Creator UserId is automatically set and cannot be updated"); + } + + String currentCreatorFullName = currentResource.getCreatorFullName(); + String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); + + if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { + log.warn("Resource Creator fullname is automatically set and cannot be updated"); + } + + String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); + String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); + + if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { + log.warn("Resource LastUpdater userId is automatically set and cannot be updated"); + } + + String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); + String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); + + if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { + log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + + Long currentCreationDate = currentResource.getCreationDate(); + Long updatedCreationDate = updateInfoResource.getCreationDate(); + + if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { + log.warn("Resource Creation date is automatically set and cannot be updated"); + } + + Long currentLastUpdateDate = currentResource.getLastUpdateDate(); + Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); + + if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { + log.warn("Resource last update date is automatically set and cannot be updated"); + } + + LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); + LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); + + if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { + log.warn("Resource lifecycle state date is automatically set and cannot be updated"); + } + + Boolean currentAbstract = currentResource.isAbstract(); + Boolean updatedAbstract = updateInfoResource.isAbstract(); + + if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { + log.warn("Resource abstract is automatically set and cannot be updated"); + } + + Boolean currentHighestVersion = currentResource.isHighestVersion(); + Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); + + if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { + log.warn("Resource highest version is automatically set and cannot be updated"); + } + + String currentUuid = currentResource.getUUID(); + String updatedUuid = updateInfoResource.getUUID(); + + if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { + log.warn("Resource UUID is automatically set and cannot be updated"); + } + + ResourceTypeEnum currentResourceType = currentResource.getResourceType(); + ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType(); + + if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) { + log.warn("Resource Type cannot be updated"); + + } + updateInfoResource.setResourceType(currentResource.getResourceType()); + + String currentInvariantUuid = currentResource.getInvariantUUID(); + String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Resource invariant UUID is automatically set and cannot be updated"); + updateInfoResource.setInvariantUUID(currentInvariantUuid); + } + return Either.left(true); + } + + + private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { + String resourceNameUpdated = updateInfoResource.getName(); + String resourceNameCurrent = currentResource.getName(); + if (resourceNameCurrent.equals(resourceNameUpdated)) + return true; + // In case of CVFC type we should support the case of old VF with CVFC + // instances that were created without the "Cvfc" suffix + return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) && + resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); + } + + private String addCvfcSuffixToResourceName(String resourceName) { + return resourceName + "Cvfc"; + } + + private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified, boolean isNested) { + String resourceNameUpdated = updateInfoResource.getName(); + if (!isResourceNameEquals(currentResource, updateInfoResource)) { + if (isNested || !hasBeenCertified) { + Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, + updateInfoResource, null); + if (validateResourceNameResponse.isRight()) { + ResponseFormat errorResponse = validateResourceNameResponse.right().value(); + return Either.right(errorResponse); + } + validateResourceNameResponse = validateResourceNameExists(updateInfoResource); + if (validateResourceNameResponse.isRight()) { + ResponseFormat errorResponse = validateResourceNameResponse.right().value(); + return Either.right(errorResponse); + } + currentResource.setName(resourceNameUpdated); + currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); + currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); + + } else { + log.info("Resource name: {}, cannot be updated once the resource has been certified once.", + resourceNameUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified) { + String iconUpdated = updateInfoResource.getIcon(); + String iconCurrent = currentResource.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null); + if (validateIcon.isRight()) { + ResponseFormat errorResponse = validateIcon.right().value(); + return Either.right(errorResponse); + } + } else { + log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified) { + String vendorNameUpdated = updateInfoResource.getVendorName(); + String vendorNameCurrent = currentResource.getVendorName(); + if (!vendorNameCurrent.equals(vendorNameUpdated)) { + if(updateInfoResource.getResourceType().equals(ResourceTypeEnum.VF) && hasBeenCertified ){ + log.info("Vendor name {} cannot be updated once the resource has been certified once.", + vendorNameUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + + } + else { + Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null); + if (validateVendorName.isRight()) { + ResponseFormat errorResponse = validateVendorName.right().value(); + return Either.right(errorResponse); + } + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, + Resource updateInfoResource) { + String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); + String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); + if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { + Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, + updateInfoResource, null); + if (validateResourceVendorModelNumber.isRight()) { + ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value(); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified, boolean inTransaction) { + Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, + inTransaction); + if (validateCategoryName.isRight()) { + ResponseFormat errorResponse = validateCategoryName.right().value(); + return Either.right(errorResponse); + } + if (hasBeenCertified) { + CategoryDefinition currentCategory = currentResource.getCategories().get(0); + SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0); + CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0); + SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0); + if (!currentCategory.getName().equals(updateCategory.getName()) + || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) { + log.info("Category {} cannot be updated once the resource has been certified once.", + currentResource.getCategories()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { + + List<String> currentDerivedFrom = currentResource.getDerivedFrom(); + List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } + + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, + updateInfoResource, null); + if (validateDerivedFromExistsEither.isRight()) { + return validateDerivedFromExistsEither; + } + } else { + Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } else { + // For derived from, we must know whether it was actually changed, + // otherwise we must do no action. + // Due to changes it inflicts on data model (remove artifacts, + // properties...), it's not like a flat field which can be + // overwritten if not changed. + // So we must indicate that derived from is not changed + updateInfoResource.setDerivedFrom(null); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { + + List<String> currentDerivedFrom = currentResource.getDerivedFrom(); + List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } + + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, + updateInfoResource, null); + if (validateDerivedFromExistsEither.isRight()) { + return validateDerivedFromExistsEither; + } + } else { + Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, + AuditingActionEnum actionEnum) { + + if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { + return Either.left(true); + } + + + String templateName = resource.getDerivedFrom().get(0); + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExists(templateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); + log.debug("request to data model failed with error: {}", storageStatus); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } else if (!dataModelResponse.left().value()) { + log.info("resource template with name: {}, does not exists", templateName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + + return Either.right(responseFormat); + + } + return Either.left(true); + } + + // Tal G for extending inheritance US815447 + private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, + Resource updateInfoResource, AuditingActionEnum actionEnum) { + String currentTemplateName = currentResource.getDerivedFrom().get(0); + String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right().value(); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus), currentResource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + return Either.right(responseFormat); + } + + if (!dataModelResponse.left().value()) { + log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, + currentTemplateName); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + + return Either.right(responseFormat); + + } + return Either.left(true); + } + + public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, + AuditingActionEnum actionEnum) { + log.debug("validate resource derivedFrom field"); + if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) + || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { + log.info("derived from (template) field is missing for the resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) { + + Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), + resource.getComponentType()); + if (resourceOperationResponse.isLeft()) { + if (!resourceOperationResponse.left().value()) { + return Either.left(false); + } else { + log.debug("resource with name: {}, already exists", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), + resource.getName()); + return Either.right(errorResponse); + } + } + log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value())); + return Either.right(errorResponse); + } + + + private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + + List<CategoryDefinition> categories = resource.getCategories(); + if (categories == null || categories.size() == 0) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + if (categories.size() > 1) { + log.debug("Must be only one category for resource"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); + return Either.right(responseFormat); + } + CategoryDefinition category = categories.get(0); + List<SubCategoryDefinition> subcategories = category.getSubcategories(); + if (subcategories == null || subcategories.size() == 0) { + log.debug("Missinig subcategory for resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + return Either.right(responseFormat); + } + if (subcategories.size() > 1) { + log.debug("Must be only one sub category for resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); + return Either.right(responseFormat); + } + + SubCategoryDefinition subcategory = subcategories.get(0); + + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction); + if (validateCategory.isRight()) { + ResponseFormat responseFormat = validateCategory.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, + SubCategoryDefinition subcategory, boolean inTransaction) { + if (category != null && subcategory != null) { + log.debug("validating resource category {} against valid categories list", category); + Either<List<CategoryDefinition>, ActionStatus> categories = elementDao + .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); + if (categories.isRight()) { + log.debug("failed to retrive resource categories from Titan"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value()); + return Either.right(responseFormat); + } + List<CategoryDefinition> categoryList = categories.left().value(); + for (CategoryDefinition cat : categoryList) { + if (cat.getName().equals(category.getName())) { + for (SubCategoryDefinition subcat : cat.getSubcategories()) { + if (subcat.getName().equals(subcategory.getName())) { + return Either.left(true); + } + } + log.debug( + "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", + subcategory, cat.getSubcategories()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue())); + } + } + log.debug("Category {} is not part of resource category group. Resource category valid values are {}", + category, categoryList); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue())); + } + return Either.left(false); + } + + public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, + AuditingActionEnum actionEnum) { + String vendorRelease = resource.getVendorRelease(); + + log.debug("validate vendor relese name"); + if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { + log.info("vendor relese name is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease); + if (validateVendorReleaseResponse.isRight()) { + ResponseFormat responseFormat = validateVendorReleaseResponse.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateVendorReleaseResponse; + } + + public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) { + if (vendorRelease != null) { + if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { + log.info("vendor release exceds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateVendorRelease(vendorRelease)) { + log.info("vendor release is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + + } + + private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, + AuditingActionEnum actionEnum) { + String vendorName = resource.getVendorName(); + if (!ValidationUtils.validateStringNotEmpty(vendorName)) { + log.info("vendor name is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName); + if (validateVendorNameResponse.isRight()) { + ResponseFormat responseFormat = validateVendorNameResponse.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateVendorNameResponse; + + } + + private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, + AuditingActionEnum actionEnum) { + String resourceVendorModelNumber = resource.getResourceVendorModelNumber(); + Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber( + resourceVendorModelNumber); + if (validateResourceVendorModelNumber.isRight()) { + ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateResourceVendorModelNumber; + + } + + private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) { + if (vendorName != null) { + if (!ValidationUtils.validateVendorNameLength(vendorName)) { + log.info("vendor name exceds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, + "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateVendorName(vendorName)) { + log.info("vendor name is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); + return Either.right(errorResponse); + } + return Either.left(true); + + } + return Either.left(false); + + } + + private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) { + if (StringUtils.isEmpty(resourceVendorModelNumber)) { + return Either.left(true); + } else { + if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) { + log.info("resource vendor model number exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, + "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + return Either.right(errorResponse); + } + // resource vendor model number is currently validated as vendor + // name + if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) { + log.info("resource vendor model number is not valid."); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + + private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) { + String cost = resource.getCost(); + if (cost != null) { + + if (!ValidationUtils.validateCost(cost)) { + log.debug("resource cost is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, + AuditingActionEnum actionEnum) { + log.debug("validate licenseType"); + String licenseType = resource.getLicenseType(); + if (licenseType != null) { + List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration() + .getLicenseTypes(); + if (!licenseTypes.contains(licenseType)) { + log.debug("License type {} isn't configured"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + if (actionEnum != null) { + // In update case, no audit is required + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return Either.right(responseFormat); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, + Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) { + Either<Operation, ResponseFormat> deleteArtifactByInterface = null; + if (updatedResource.getDerivedFrom() != null) { + log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); + log.debug("1. Removing interface artifacts from graph"); + // Remove all interface artifacts of resource + String resourceId = updatedResource.getUniqueId(); + Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces(); + + if (interfaces != null) { + Collection<InterfaceDefinition> values = interfaces.values(); + for (InterfaceDefinition interfaceDefinition : values) { + String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); + + log.trace("Starting interface artifacts removal for interface type {}", interfaceType); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); + if (operations != null) { + for (Entry<String, Operation> operationEntry : operations.entrySet()) { + Operation operation = operationEntry.getValue(); + ArtifactDefinition implementation = operation.getImplementationArtifact(); + if (implementation != null) { + String uniqueId = implementation.getUniqueId(); + log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", + uniqueId, operationEntry.getKey(), interfaceType); + // only thing that transacts and locks here + deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, + userId, uniqueId, + true); + if (deleteArtifactByInterface.isRight()) { + log.debug("Couldn't remove artifact definition with id {}", uniqueId); + if (!inTransaction) { + titanDao.rollback(); + } + return Either.right(deleteArtifactByInterface.right().value()); + } + } else { + log.trace("No implementation found for operation {} - nothing to delete", + operationEntry.getKey()); + } + } + } else { + log.trace("No operations found for interface type {}", interfaceType); + } + } + } + log.debug("2. Removing properties"); + Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation + .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); + + if (findPropertiesOfNode.isRight() + && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { + log.debug("Failed to remove all properties of resource"); + if (!inTransaction) + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); + } + + } else { + log.debug("Derived from wasn't changed during update"); + } + + if (!inTransaction) + titanDao.commit(); + return Either.left(true); + + } + + /**** Auditing *******************/ + + protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + public ICapabilityTypeOperation getCapabilityTypeOperation() { + return capabilityTypeOperation; + } + + public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { + this.capabilityTypeOperation = capabilityTypeOperation; + } + + public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) { + log.debug("validate resource properties default values"); + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + List<PropertyDefinition> properties = resource.getProperties(); + String type = null; + String innerType = null; + if (properties != null) { + for (PropertyDefinition property : properties) { + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + eitherResult = Either.right(responseFormat); + break; + } + + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes( + applicationDataTypeCache); + if (allDataTypes.isRight()) { + return Either.right(allDataTypes.right().value()); + } + + type = property.getType(); + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation + .isPropertyInnerTypeValid(property, allDataTypes.left().value()); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight().booleanValue()) { + log.info("Invalid inner type for property"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + eitherResult = Either.right(responseFormat); + break; + } + } + + if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) { + log.info("Invalid default value for property"); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, + property.getName(), type, innerType, property.getDefaultValue()); + } else { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, + property.getName(), type, property.getDefaultValue()); + } + eitherResult = Either.right(responseFormat); + break; + + } + } + } + return eitherResult; + } + + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + private String getComponentTypeForResponse(Component component) { + String componentTypeForResponse = "SERVICE"; + if (component instanceof Resource) { + componentTypeForResponse = ((Resource) component).getResourceType().name(); + } + return componentTypeForResponse; + } + + private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, + Map<String, Object> toscaJson, Resource resource) { + + Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>(); + Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups); + + Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS); + if (eitherNodesTemlates.isLeft()) { + Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value(); + + if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) { + Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry<String, Object> groupNameValue = nodesNameValue.next(); + + String groupName = groupNameValue.getKey(); + Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, + groupNameValue.getValue()); + if (eitherNode.isRight()) { + String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + + resource.getName(); + BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, + ErrorSeverity.INFO); + return Either.right(eitherNode.right().value()); + } else { + GroupDefinition groupDefinition = eitherNode.left().value(); + groups.put(groupName, groupDefinition); + } + } + } + } + + return result; + } + + private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, + Map<String, Object> toscaJson, Resource resource) { + + Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson); + if (inputs.isRight()) { + String message = "Failed when creating inputs: for resource:" + resource.getName(); + BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); + Map<String, InputDefinition> resultMap = new HashMap<>(); + return Either.left(resultMap); + + } + + Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value()); + + return result; + } + + @SuppressWarnings("unchecked") + private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) { + + GroupDefinition groupInfo = new GroupDefinition(); + groupInfo.setName(groupName); + Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo); + + try { + if (groupTemplateJson != null && groupTemplateJson instanceof Map) { + Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson; + String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); + if (!StringUtils.isEmpty(groupType)) { + groupInfo.setType(groupType); + } else { + log.debug("The 'type' member is not found under group {}", groupName); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName)); + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + groupInfo.setDescription( + (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) { + Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName()); + if (members != null) { + if (members instanceof List) { + Map<String, String> membersLoaded = new HashMap<>(); + List<?> membersAsList = (List<?>) members; + for (Object member : membersAsList) { + membersLoaded.put(member.toString(), ""); + } + groupInfo.setMembers(membersLoaded); + } else { + log.debug("The 'members' member is not of type list under group {}", groupName); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + } + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName()); + + Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml( + properties, groupName, groupType); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + groupInfo.convertFromGroupProperties(regResponse.left().value()); + } + } + + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group"); + log.debug("error when creating group, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + @SuppressWarnings("unchecked") + private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, + String groupName, String groupType) { + + List<GroupProperty> result = new ArrayList<>(); + + if (properties == null) { + return Either.left(result); + } + + Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(groupType, true); + + if (groupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); + } + + Map<String, PropertyDefinition> gtProperties = new HashMap<>(); + GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); + + List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties(); + + if (propertiesDef != null) { + gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + } + + if (properties != null) { + + if (properties instanceof Map) { + + Map<String, Object> props = (Map<String, Object>) properties; + for (Entry<String, Object> entry : props.entrySet()) { + + String propName = entry.getKey(); + Object value = entry.getValue(); + + PropertyDefinition gtDefinition = gtProperties.get(propName); + if (gtDefinition == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, + propName, groupName, groupType)); + } + + ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType()); + + String convertedValue = null; + if (value != null) { + if (type == null || value instanceof Map || value instanceof List) { + convertedValue = gson.toJson(value); + } else { + convertedValue = value.toString(); + } + } + + GroupProperty groupProperty = new GroupProperty(); + groupProperty.setValue(convertedValue); + groupProperty.setName(propName); + + log.trace("After building group property {}", groupProperty); + + result.add(groupProperty); + } + + } + + } + + return Either.left(result); + } + + public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) { + + // validate user + if (user != null) { + Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", + false); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + } + + // get resource from csar uuid + Either<Resource, StorageOperationStatus> either = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); + if (either.isRight()) { + ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, + csarUuid); + return Either.right(resp); + } + + return Either.left(either.left().value()); + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs( + String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities( + String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, + Map<String, List<UploadCapInfo>> uploadedCapabilities) { + ResponseFormat responseFormat; + Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>(); + + for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) { + String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType(); + if (!defaultCapabilities.containsKey(capabilityType)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, + capabilityType); + return Either.right(responseFormat); + } else { + CapabilityDefinition defaultCapability; + if (CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) { + defaultCapability = defaultCapabilities.get(capabilityType).get(0); + } else { + Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade + .getToscaFullElement(resourceId); + if (getFullComponentRes.isRight()) { + log.debug("Failed to get full component {}. Status is {}. ", resourceId, + getFullComponentRes.right().value()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, + resourceId); + return Either.right(responseFormat); + } + defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); + } + if (CollectionUtils.isEmpty(defaultCapability.getProperties()) + && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) { + log.debug("Failed to validate capability {} of component {}. Property list is empty. ", + defaultCapability.getName(), resourceId); + log.debug( + "Failed to update capability property values. Property list of fetched capability {} is empty. ", + defaultCapability.getName()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId); + return Either.right(responseFormat); + } + if (CollectionUtils.isNotEmpty(defaultCapability.getProperties()) + && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) { + Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability( + defaultCapability, uploadedCapabilitiesEntry.getValue().get(0)); + if (validationRes.isRight()) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, + validationRes.right().value()); + return Either.right(responseFormat); + } + } + List<CapabilityDefinition> validCapabilityList = new ArrayList<>(); + validCapabilityList.add(defaultCapability); + validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList); + } + } + return Either.left(validCapabilitiesMap); + } + + private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability( + CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { + List<ComponentInstanceProperty> validProperties = new ArrayList<>(); + Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream() + .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties(); + for (UploadPropInfo property : uploadedProperties) { + String propertyName = property.getName().toLowerCase(); + String propertyType = property.getType(); + ComponentInstanceProperty validProperty; + if (defaultProperties.containsKey(propertyName)) { + if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) { + return Either.right(propertyName); + } + } + validProperty = new ComponentInstanceProperty(); + validProperty.setName(propertyName); + if (property.getValue() != null) + validProperty.setValue(property.getValue().toString()); + validProperty.setDescription(property.getDescription()); + validProperty.setPassword(property.isPassword()); + validProperties.add(validProperty); + } + defaultCapability.setProperties(validProperties); + return Either.left(true); + } + + private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( + List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, + Resource resource, User user) { + + EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>( + ArtifactOperationEnum.class); + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either + .left(nodeTypeArtifactsToHandle); + ; + try { + // add all found Csar artifacts to list to upload + List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList); + List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>(); + List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>(); + for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { + ArtifactDefinition foundArtifact; + + if (!existingArtifactsToHandle.isEmpty()) { + foundArtifact = existingArtifactsToHandle.stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() + .orElse(null); + if (foundArtifact != null) { + if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact + .getArtifactType()) { + if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { + currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); + // if current artifact already exists, but has + // different content, add him to the list to + // update + artifactsToUpdate.add(currNewArtifact); + } + // remove found artifact from the list of existing + // artifacts to handle, because it was already + // handled + existingArtifactsToHandle.remove(foundArtifact); + // and remove found artifact from the list to + // upload, because it should either be updated or be + // ignored + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", + currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(), + foundArtifact.getArtifactType()); + AuditingActionEnum auditingAction = artifactsBusinessLogic + .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); + artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), + user, null, null, foundArtifact.getUniqueId(), responseFormat, + resource.getComponentType(), null); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + for (ArtifactDefinition currArtifact : existingArtifactsToHandle) { + if (currArtifact.getIsFromCsar()) { + artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + } else { + artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + + } + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, + String nodeTypeFullName) { + String actualType; + String actualVfName; + if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) { + actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); + actualType = ResourceTypeEnum.VFC.name(); + } else { + actualVfName = vfResourceName; + actualType = nodeResourceType; + } + + StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + String nameWithouNamespacePrefix = nodeTypeFullName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); + + if (actualName.startsWith(Constants.ABSTRACT)) { + toscaResourceName.append(resourceType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)); + } else { + toscaResourceName.append(actualType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); + } + StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), + previousToscaResourceName + .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()) + .toString()); + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + ///////////////////////////////////////// DataModel + ///////////////////////////////////////// refactoring///////////////////////////////////////////// + @Override + public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, + List<String> dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, + paramsToRetuen); + + if (resourceResultEither.isRight()) { + if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found resource with id {} ", resourceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + } + + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); + } + + Resource resource = resourceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, + dataParamsToReturn); + return Either.left(dataTransfer); + } + + @Override + public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) { + Resource resource = (Resource) clonedComponent; + if (ModelConverter.isAtomicComponent(resource.getResourceType())) { + Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade + .shouldUpgradeToLatestDerived(resource); + if (shouldUpgradeToLatestDerived.isRight()) { + return Either.right( + componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value())); + } + return Either.left(shouldUpgradeToLatestDerived.left().value()); + } else { + return super.shouldUpgradeToLatestDerived(clonedComponent); + } + } + + +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index 7ed90ce3b6..97dcf35c96 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -20,25 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.Constants; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; @@ -71,8 +58,9 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -82,882 +70,919 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; @Component("resourceImportManager") public class ResourceImportManager { - private ServletContext servletContext; - - @Autowired - private IAuditingManager auditingManager; - - @Autowired - private ResourceBusinessLogic resourceBusinessLogic; - - @Autowired - private IGraphLockOperation graphLockOperation; - - @Autowired - protected ComponentsUtils componentsUtils; - - public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern - .compile("[\\w\\-\\_\\d\\:]+"); - @Autowired - protected CapabilityTypeOperation capabilityTypeOperation; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - private ResponseFormatManager responseFormatManager; - - private static Logger log = LoggerFactory.getLogger(ResourceImportManager.class.getName()); - - public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { - this.toscaOperationFacade = toscaOperationFacade; - } - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - lifecycleChangeInfo.setUserRemarks("certification on import"); - Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); - } - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - lifecycleChangeInfo.setUserRemarks("certification on import"); - Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); - } - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { - Resource resource = new Resource(); - ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); - - String latestCertifiedResourceId = null; - try { - boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty(); - setConstantMetaData(resource, shouldBeCertified); - setMetaDataFromJson(resourceMetaData, resource); - - Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - return Either.right(validationErrorResponse); - - } - - Either<Boolean, ResponseFormat> isValidResource = validationFunction.apply(resource); - if (isValidResource.isLeft()) { - // The flag createNewVersion if false doesn't create new version - if (!createNewVersion) { - Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName()); - if (latestByName.isLeft()) { - return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); - } - } - - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested); - Either<Resource, ResponseFormat> changeStateResponse; - if (response.isLeft()) { - resource = response.left().value().left; - - if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){ - Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = - resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - latestCertifiedResourceId = getLatestCertifiedResourceId(resource); - changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); - if (changeStateResponse.isRight()) { - response = Either.right(changeStateResponse.right().value()); - } else { - responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right); - response = Either.left(responsePair); - } - } - } else { - ResponseFormat validationErrorResponse = isValidResource.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - response = Either.right(validationErrorResponse); - } - - } catch (RuntimeException e) { - ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e); - response = Either.right(exceptionResponse); - } finally { - if (latestCertifiedResourceId != null && needLock) { - log.debug("unlock resource {}", latestCertifiedResourceId); - graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); - } - } - - return response; - } - - private String getLatestCertifiedResourceId(Resource resource) { - Map<String, String> allVersions = resource.getAllVersions(); - Double latestCertifiedVersion = 0.0; - if (allVersions != null) { - for (String version : allVersions.keySet()) { - Double dVersion = Double.valueOf(version); - if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) { - latestCertifiedVersion = dVersion; - } - } - return allVersions.get(String.valueOf(latestCertifiedVersion)); - } else { - return null; - } - } - - public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isReusable, boolean isInTransaction) { - - Resource resource = new Resource(); - ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED); - Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); - - try { - setMetaDataFromJson(resourceMetaData, resource); - - Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - return Either.right(validationErrorResponse); - - } - - // currently import VF isn't supported. In future will be supported - // import VF only with CSER file!! - if (ResourceTypeEnum.VF.equals(resource.getResourceType())) { - log.debug("Now import VF isn't supported. It will be supported in future with CSER file only"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - - Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - if (validatePropertiesTypes.isLeft()) { - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); - } else { - ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - response = Either.right(validationErrorResponse); - } - - } catch (RuntimeException e) { - ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e); - response = Either.right(exceptionResponse); - } - - return response; - - } - - Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) { - @SuppressWarnings("unchecked") - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml); - Map<String, Object> toscaJson = toscaJsonAll; - - // Checks if exist and builds the node_types map - if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) { - toscaJson = new HashMap<String, Object>(); - toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName())); - } - // Derived From - Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource, inTransaction); - if (setDerivedFrom.isRight()) { - return Either.right(setDerivedFrom.right().value()); - } - Resource parentResource = setDerivedFrom.left().value(); - if(StringUtils.isEmpty(resource.getToscaResourceName())) - setToscaResourceName(toscaJson, resource); - setAttributes(toscaJson, resource); - eitherResult = setCapabilities(toscaJson, resource, parentResource); - if (eitherResult.isRight()) - return eitherResult; - eitherResult = setProperties(toscaJson, resource); - if (eitherResult.isRight()) - return eitherResult; - eitherResult = setRequirements(toscaJson, resource, parentResource); - if (eitherResult.isRight()) - return eitherResult; - setInterfaceLifecycle(toscaJson, resource); - - return eitherResult; - } - - private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) { - Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) { - String toscaResourceName = toscaElement.left().value().keySet().iterator().next(); - resource.setToscaResourceName(toscaResourceName); - } - } - - private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) { - Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES); - if (toscaInterfaces.isLeft()) { - Map<String, Object> jsonInterfaces = toscaInterfaces.left().value(); - Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<String, InterfaceDefinition>(); - Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator(); - while (interfacesNameValue.hasNext()) { - Entry<String, Object> interfaceNameValue = interfacesNameValue.next(); - Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue()); - if (eitherInterface.isRight()) { - log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); - } else { - moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value()); - } - - } - if (moduleInterfaces.size() > 0) { - resource.setInterfaces(moduleInterfaces); - } - } - } - - private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(Object interfaceJson) { - InterfaceDefinition interf = new InterfaceDefinition(); - Either<InterfaceDefinition, ResultStatusEnum> result = Either.left(interf); - - try { - if (interfaceJson instanceof String) { - String requirementJsonString = (String) interfaceJson; - interf.setType(requirementJsonString); - } else if (interfaceJson instanceof Map) { - Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson; - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - interf.setType(type); - interf.setUniqueId(type.toLowerCase()); - } - } else { - result = Either.right(ResultStatusEnum.GENERAL_ERROR); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource- create interface"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); - log.debug("error when creating interface, message:{}", e.getMessage(), e); - result = Either.right(ResultStatusEnum.GENERAL_ERROR); - } - - return result; - } - - private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS); - if (toscaRequirements.isLeft()) { - List<Object> jsonRequirements = toscaRequirements.left().value(); - Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<String, List<RequirementDefinition>>(); - // Checking for name duplication - Set<String> reqNames = new HashSet<>(); - // Getting flattened list of capabilities of parent node - cap name - // to cap type - Either<Map<String, String>, ResponseFormat> reqName2Type = getReqName2Type(parentResource); - if (reqName2Type.isRight()) { - ResponseFormat responseFormat = reqName2Type.right().value(); - log.debug("Error during setting requirements of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map<String, String> reqName2TypeMap = reqName2Type.left().value(); - for (Object jsonRequirementObj : jsonRequirements) { - // Requirement - Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj; - String requirementName = requirementJsonWrapper.keySet().iterator().next(); - String reqNameLowerCase = requirementName.toLowerCase(); - if (reqNames.contains(reqNameLowerCase)) { - log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase)); - } - reqNames.add(reqNameLowerCase); - Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName)); - if (eitherRequirement.isRight()) { - log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName()); - return Either.right(eitherRequirement.right().value()); - } - RequirementDefinition requirementDef = eitherRequirement.left().value(); - requirementDef.setName(requirementName); - if (moduleRequirements.containsKey(requirementDef.getCapability())) { - moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); - } else { - List<RequirementDefinition> list = new ArrayList<RequirementDefinition>(); - list.add(requirementDef); - moduleRequirements.put(requirementDef.getCapability(), list); - } - - // Validating against req/cap of "derived from" node - Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { - log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); - } - } - if (moduleRequirements.size() > 0) { - resource.setRequirements(moduleRequirements); - } - - } - return eitherResult; - - } - - private Either<RequirementDefinition, ResponseFormat> createRequirementFromImportFile(Object requirementJson) { - RequirementDefinition requirement = new RequirementDefinition(); - Either<RequirementDefinition, ResponseFormat> result = Either.left(requirement); - - try { - if (requirementJson instanceof String) { - String requirementJsonString = (String) requirementJson; - requirement.setCapability(requirementJsonString); - } else if (requirementJson instanceof Map) { - Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson; - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { - requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); - } - - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { - requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName())); - } - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value() == true) { - requirement.setMinOccurrences(occurrencesList.get(0).toString()); - requirement.setMaxOccurrences(occurrencesList.get(1).toString()); - } - - } - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create Requirement"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement"); - log.debug("error when creating requirement, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private Either<Boolean, ResponseFormat> setProperties(Map<String, Object> toscaJson, Resource resource) { - Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson); - ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - Either<Boolean, ResponseFormat> result = Either.left(true); - Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); - if (properties.isLeft()) { - List<PropertyDefinition> propertiesList = new ArrayList<>(); - Map<String, PropertyDefinition> value = properties.left().value(); - if (value != null) { - for (Entry<String, PropertyDefinition> entry : value.entrySet()) { - String name = entry.getKey(); - if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ - log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); - } - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - propertiesList.add(propertyDefinition); - } - } - resource.setProperties(propertiesList); - } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); - } - return result; - } - - private ResultStatusEnum setAttributes(Map<String, Object> toscaJson, Resource resource) { - ResultStatusEnum result = ResultStatusEnum.OK; - Either<Map<String, PropertyDefinition>, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); - if (attributes.isLeft()) { - List<PropertyDefinition> attributeList = new ArrayList<>(); - Map<String, PropertyDefinition> value = attributes.left().value(); - if (value != null) { - for (Entry<String, PropertyDefinition> entry : value.entrySet()) { - String name = entry.getKey(); - PropertyDefinition attributeDef = entry.getValue(); - attributeDef.setName(name); - attributeList.add(attributeDef); - } - } - resource.setAttributes(attributeList); - } else { - result = attributes.right().value(); - } - return result; - } - - private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource, boolean inTransaction) { - Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM); - Resource derivedFromResource = null; - if (toscaDerivedFromElement.isLeft()) { - String derivedFrom = toscaDerivedFromElement.left().value(); - log.debug("Derived from TOSCA name is {}", derivedFrom); - resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom })); - Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); - - if (latestByToscaResourceName.isRight()) { - StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); - if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { - operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; - } - log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); - ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); - return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom)); - } - derivedFromResource = latestByToscaResourceName.left().value(); - } - return Either.left(derivedFromResource); - } - - private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES); - if (toscaCapabilities.isLeft()) { - Map<String, Object> jsonCapabilities = toscaCapabilities.left().value(); - Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<String, List<CapabilityDefinition>>(); - Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator(); - Set<String> capNames = new HashSet<>(); - // Getting flattened list of capabilities of parent node - cap name - // to cap type - Either<Map<String, String>, ResponseFormat> capName2Type = getCapName2Type(parentResource); - if (capName2Type.isRight()) { - ResponseFormat responseFormat = capName2Type.right().value(); - log.debug("Error during setting capabilities of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map<String, String> capName2TypeMap = capName2Type.left().value(); - while (capabilitiesNameValue.hasNext()) { - Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next(); - - // Validating that no req/cap duplicates exist in imported YAML - String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); - if (capNames.contains(capNameLowerCase)) { - log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase)); - } - capNames.add(capNameLowerCase); - - Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue()); - if (eitherCapability.isRight()) { - log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName()); - return Either.right(eitherCapability.right().value()); - } - - CapabilityDefinition capabilityDef = eitherCapability.left().value(); - capabilityDef.setName(capabilityNameValue.getKey()); - if (moduleCapabilities.containsKey(capabilityDef.getType())) { - moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); - } else { - List<CapabilityDefinition> list = new ArrayList<CapabilityDefinition>(); - list.add(capabilityDef); - moduleCapabilities.put(capabilityDef.getType(), list); - } - - // Validating against req/cap of "derived from" node - Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { - // Here parentResource is for sure not null, so it's - // null-safe - log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); - } - } - if (moduleCapabilities.size() > 0) { - resource.setCapabilities(moduleCapabilities); - } - } - - return eitherResult; - - } - - private Either<Map<String, String>, ResponseFormat> getCapName2Type(Resource parentResource) { - Map<String, String> capName2type = new HashMap<>(); - if (parentResource != null) { - Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities(); - if (capabilities != null) { - for (List<CapabilityDefinition> capDefinitions : capabilities.values()) { - for (CapabilityDefinition capDefinition : capDefinitions) { - String nameLowerCase = capDefinition.getName().toLowerCase(); - if (capName2type.get(nameLowerCase) != null) { - String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); - BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - capName2type.put(nameLowerCase, capDefinition.getType()); - } - } - } - } - return Either.left(capName2type); - } - - private Either<Map<String, String>, ResponseFormat> getReqName2Type(Resource parentResource) { - Map<String, String> reqName2type = new HashMap<>(); - if (parentResource != null) { - Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements(); - if (requirements != null) { - for (List<RequirementDefinition> reqDefinitions : requirements.values()) { - for (RequirementDefinition reqDefinition : reqDefinitions) { - String nameLowerCase = reqDefinition.getName().toLowerCase(); - if (reqName2type.get(nameLowerCase) != null) { - String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); - BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - reqName2type.put(nameLowerCase, reqDefinition.getCapability()); - } - } - } - } - return Either.left(reqName2type); - } - - private Either<Boolean, ResponseFormat> validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) { - String capNameLowerCase = reqCapName.toLowerCase(); - log.trace("Validating capability {} vs parent resource", capNameLowerCase); - String parentCapType = parentCapName2Type.get(capNameLowerCase); - if (parentCapType != null) { - if (childCapabilityType.equals(parentCapType)) { - log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); - return Either.left(true); - } - Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); - if (capabilityTypeDerivedFrom.isRight()) { - log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value())); - return Either.right(responseFormat); - } - return Either.left(capabilityTypeDerivedFrom.left().value()); - } - return Either.left(true); - } - - private Either<CapabilityDefinition, ResponseFormat> createCapabilityFromImportFile(Object capabilityJson) { - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - Either<CapabilityDefinition, ResponseFormat> result = Either.left(capabilityDefinition); - - try { - if (capabilityJson instanceof String) { - String capabilityJsonString = (String) capabilityJson; - capabilityDefinition.setType(capabilityJsonString); - } else if (capabilityJson instanceof Map) { - Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson; - // Type - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); - } - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value() == true) { - capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); - capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); - } - } - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - - Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); - if (propertiesRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); - return result; - } else { - propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); - List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); - capabilityDefinition.setProperties(capabilityProperties); - } - } - } else if (!(capabilityJson instanceof List)) { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); - log.debug("error when creating capability, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { - String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : ""; - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource " + payloadName); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName); - - log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e); - ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); - auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative); - return errorResponseWrapper; - } - - private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus()); - String message = ""; - if (errorResponseWrapper.getMessageId() != null) { - message = errorResponseWrapper.getMessageId() + ": "; - } - message += errorResponseWrapper.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); - - String version, lifeCycleState; - if (isNormative) { - version = Constants.FIRST_CERTIFIED_VERSION_VERSION; - lifeCycleState = LifecycleStateEnum.CERTIFIED.name(); - } else { - version = ""; - lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); - - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); - - getAuditingManager().auditEvent(auditingFields); - } - - private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) { - resource.setTags(resourceMetaData.getTags()); - List<CategoryDefinition> categories = resourceMetaData.getCategories(); - resource.setCategories(categories); - resource.setDescription(resourceMetaData.getDescription()); - resource.setIcon(resourceMetaData.getResourceIconPath()); - resource.setName(resourceMetaData.getName()); - if (categories != null && !categories.isEmpty()) { - CategoryDefinition categoryDef = categories.get(0); - resource.setAbstract(false); - if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) { - SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); - if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) { - resource.setAbstract(true); - } - } - } - resource.setContactId(resourceMetaData.getContactId()); - resource.setCreatorUserId(resourceMetaData.getContactId()); - - if (resourceMetaData.getVendorName() != null) { - resource.setVendorName(resourceMetaData.getVendorName()); - } - - if (resourceMetaData.getVendorRelease() != null) { - resource.setVendorRelease(resourceMetaData.getVendorRelease()); - } - - resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType())); - - } - - private void setConstantMetaData(Resource resource, boolean shouldBeCertified) { - String version; - LifecycleStateEnum state; - if(shouldBeCertified){ - version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION; - state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; - }else{ - version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; - state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; - } - resource.setVersion(version); - resource.setLifecycleState(state); - resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); - resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); - - } - - private Either<Boolean, ResponseFormat> validateOccurrences(List<Object> occurrensesList) { - - if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { - log.debug("Occurrenses list empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (occurrensesList.size() < 2) { - log.debug("Occurrenses list size not 2"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - Object minObj = occurrensesList.get(0); - Object maxObj = occurrensesList.get(1); - Integer minOccurrences = null; - Integer maxOccurrences = null; - if (minObj instanceof Integer) - minOccurrences = (Integer) minObj; - else { - log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - if (minOccurrences < 0) { - log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (maxObj instanceof String) { - if (maxObj.equals("UNBOUNDED")) { - return Either.left(true); - } else { - log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - } else { - if (maxObj instanceof Integer) - maxOccurrences = (Integer) maxObj; - else { - log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { - log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - } - - return Either.left(true); - - } - - public void init(ServletContext servletContext) { - if (this.servletContext == null) { - synchronized (this) { - if (this.servletContext == null) { - this.servletContext = servletContext; - responseFormatManager = ResponseFormatManager.getInstance(); - resourceBusinessLogic = getResourceBL(servletContext); - } - } - } - } - - public boolean isResourceExist(String resourceName) { - return resourceBusinessLogic.isResourceExist(resourceName); - } - - private ResourceBusinessLogic getResourceBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class); - return resourceBl; - } - - public ServletContext getServletContext() { - return servletContext; - } - - public IAuditingManager getAuditingManager() { - return auditingManager; - } - - public ResponseFormatManager getResponseFormatManager() { - return responseFormatManager; - } - - public void setResponseFormatManager(ResponseFormatManager responseFormatManager) { - this.responseFormatManager = responseFormatManager; - } - - public ResourceBusinessLogic getResourceBusinessLogic() { - return resourceBusinessLogic; - } - - public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) { - this.resourceBusinessLogic = resourceBusinessLogic; - } - - public Logger getLog() { - return log; - } - - public static void setLog(Logger log) { - ResourceImportManager.log = log; - } - - public IGraphLockOperation getGraphLockOperation() { - return graphLockOperation; - } - - public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { - this.graphLockOperation = graphLockOperation; - } - - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - - public void setAuditingManager(IAuditingManager auditingManager) { - this.auditingManager = auditingManager; - } + private ServletContext servletContext; + + @Autowired + private AuditingManager auditingManager; + + @Autowired + private ResourceBusinessLogic resourceBusinessLogic; + + @Autowired + private IGraphLockOperation graphLockOperation; + + @Autowired + protected ComponentsUtils componentsUtils; + + public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern + .compile("[\\w\\-\\_\\d\\:]+"); + @Autowired + protected CapabilityTypeOperation capabilityTypeOperation; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + private ResponseFormatManager responseFormatManager; + + private static final Logger log = LoggerFactory.getLogger(ResourceImportManager.class); + + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + lifecycleChangeInfo.setUserRemarks("certification on import"); + Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + } + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + lifecycleChangeInfo.setUserRemarks("certification on import"); + Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + } + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { + Resource resource = new Resource(); + ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); + + String latestCertifiedResourceId = null; + try { + boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty(); + setConstantMetaData(resource, shouldBeCertified); + setMetaDataFromJson(resourceMetaData, resource); + + Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); + if (validateResourceFromYaml.isRight()) { + ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); + return Either.right(validationErrorResponse); + + } + + Either<Boolean, ResponseFormat> isValidResource = validationFunction.apply(resource); + if (isValidResource.isLeft()) { + // The flag createNewVersion if false doesn't create new version + if (!createNewVersion) { + Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName()); + if (latestByName.isLeft()) { + return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); + } + } + + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested); + Either<Resource, ResponseFormat> changeStateResponse; + if (response.isLeft()) { + resource = response.left().value().left; + + if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){ + Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = + resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); + if(handleNodeTypeArtifactsRes.isRight()){ + return Either.right(handleNodeTypeArtifactsRes.right().value()); + } + } + latestCertifiedResourceId = getLatestCertifiedResourceId(resource); + changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); + if (changeStateResponse.isRight()) { + response = Either.right(changeStateResponse.right().value()); + } else { + responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right); + response = Either.left(responsePair); + } + } + } else { + ResponseFormat validationErrorResponse = isValidResource.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); + response = Either.right(validationErrorResponse); + } + + } catch (RuntimeException e) { + ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e); + response = Either.right(exceptionResponse); + } finally { + if (latestCertifiedResourceId != null && needLock) { + log.debug("unlock resource {}", latestCertifiedResourceId); + graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); + } + } + + return response; + } + + private String getLatestCertifiedResourceId(Resource resource) { + Map<String, String> allVersions = resource.getAllVersions(); + Double latestCertifiedVersion = 0.0; + if (allVersions != null) { + for (String version : allVersions.keySet()) { + Double dVersion = Double.valueOf(version); + if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) { + latestCertifiedVersion = dVersion; + } + } + return allVersions.get(String.valueOf(latestCertifiedVersion)); + } else { + return null; + } + } + + public void populateResourceMetadata(UploadResourceInfo resourceMetaData, Resource resource) { + if (resource != null && resourceMetaData != null) { + resource.setDescription(resourceMetaData.getDescription()); + resource.setTags(resourceMetaData.getTags()); + resource.setCategories(resourceMetaData.getCategories()); + resource.setContactId(resourceMetaData.getContactId()); + resource.setName(resourceMetaData.getName()); + resource.setIcon(resourceMetaData.getResourceIconPath()); + resource.setResourceVendorModelNumber(resourceMetaData.getResourceVendorModelNumber()); + resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType())); + if (resourceMetaData.getVendorName() != null) { + resource.setVendorName(resourceMetaData.getVendorName()); + } + if (resourceMetaData.getVendorRelease() != null) { + resource.setVendorRelease(resourceMetaData.getVendorRelease()); + } + } + } + + public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) { + + Resource resource = new Resource(); + ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED); + Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair); + + try { + setMetaDataFromJson(resourceMetaData, resource); + + Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); + if (validateResourceFromYaml.isRight()) { + ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); + return Either.right(validationErrorResponse); + + } + + // currently import VF isn't supported. In future will be supported + // import VF only with CSER file!! + if (ResourceTypeEnum.VF.equals(resource.getResourceType())) { + log.debug("Now import VF isn't supported. It will be supported in future with CSER file only"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + + Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + if (validatePropertiesTypes.isLeft()) { + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); + } else { + ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); + response = Either.right(validationErrorResponse); + } + + } catch (RuntimeException e) { + ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e); + response = Either.right(exceptionResponse); + } + + return response; + + } + + Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource) { + @SuppressWarnings("unchecked") + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml); + Map<String, Object> toscaJson = toscaJsonAll; + + // Checks if exist and builds the node_types map + if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) { + toscaJson = new HashMap<String, Object>(); + toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName())); + } + // Derived From + Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource); + if (setDerivedFrom.isRight()) { + return Either.right(setDerivedFrom.right().value()); + } + Resource parentResource = setDerivedFrom.left().value(); + if(StringUtils.isEmpty(resource.getToscaResourceName())) { + setToscaResourceName(toscaJson, resource); + } + setAttributes(toscaJson, resource); + eitherResult = setCapabilities(toscaJson, resource, parentResource); + if (eitherResult.isRight()) { + return eitherResult; + } + eitherResult = setProperties(toscaJson, resource); + if (eitherResult.isRight()) { + return eitherResult; + } + eitherResult = setRequirements(toscaJson, resource, parentResource); + if (eitherResult.isRight()) { + return eitherResult; + } + setInterfaceLifecycle(toscaJson, resource); + + return eitherResult; + } + + private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) { + Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) { + String toscaResourceName = toscaElement.left().value().keySet().iterator().next(); + resource.setToscaResourceName(toscaResourceName); + } + } + + private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) { + Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES); + if (toscaInterfaces.isLeft()) { + Map<String, Object> jsonInterfaces = toscaInterfaces.left().value(); + Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<String, InterfaceDefinition>(); + Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator(); + while (interfacesNameValue.hasNext()) { + Entry<String, Object> interfaceNameValue = interfacesNameValue.next(); + Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue()); + if (eitherInterface.isRight()) { + log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); + } else { + moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value()); + } + + } + if (moduleInterfaces.size() > 0) { + resource.setInterfaces(moduleInterfaces); + } + } + } + + private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(Object interfaceJson) { + InterfaceDefinition interf = new InterfaceDefinition(); + Either<InterfaceDefinition, ResultStatusEnum> result = Either.left(interf); + + try { + if (interfaceJson instanceof String) { + String requirementJsonString = (String) interfaceJson; + interf.setType(requirementJsonString); + } else if (interfaceJson instanceof Map) { + Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson; + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); + interf.setType(type); + interf.setUniqueId(type.toLowerCase()); + } + } else { + result = Either.right(ResultStatusEnum.GENERAL_ERROR); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); + log.debug("error when creating interface, message:{}", e.getMessage(), e); + result = Either.right(ResultStatusEnum.GENERAL_ERROR); + } + + return result; + } + + private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS); + if (toscaRequirements.isLeft()) { + List<Object> jsonRequirements = toscaRequirements.left().value(); + Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<String, List<RequirementDefinition>>(); + // Checking for name duplication + Set<String> reqNames = new HashSet<>(); + // Getting flattened list of capabilities of parent node - cap name + // to cap type + Either<Map<String, String>, ResponseFormat> reqName2Type = getReqName2Type(parentResource); + if (reqName2Type.isRight()) { + ResponseFormat responseFormat = reqName2Type.right().value(); + log.debug("Error during setting requirements of imported resource: {}", responseFormat); + return Either.right(responseFormat); + } + Map<String, String> reqName2TypeMap = reqName2Type.left().value(); + for (Object jsonRequirementObj : jsonRequirements) { + // Requirement + Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj; + String requirementName = requirementJsonWrapper.keySet().iterator().next(); + String reqNameLowerCase = requirementName.toLowerCase(); + if (reqNames.contains(reqNameLowerCase)) { + log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase)); + } + reqNames.add(reqNameLowerCase); + Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName)); + if (eitherRequirement.isRight()) { + log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName()); + return Either.right(eitherRequirement.right().value()); + } + RequirementDefinition requirementDef = eitherRequirement.left().value(); + requirementDef.setName(requirementName); + if (moduleRequirements.containsKey(requirementDef.getCapability())) { + moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); + } else { + List<RequirementDefinition> list = new ArrayList<RequirementDefinition>(); + list.add(requirementDef); + moduleRequirements.put(requirementDef.getCapability(), list); + } + + // Validating against req/cap of "derived from" node + Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName()); + if (validateVsParentCap.isRight()) { + return Either.right(validateVsParentCap.right().value()); + } + if (!validateVsParentCap.left().value()) { + log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName()); + return Either.right(responseFormat); + } + } + if (moduleRequirements.size() > 0) { + resource.setRequirements(moduleRequirements); + } + + } + return eitherResult; + + } + + private Either<RequirementDefinition, ResponseFormat> createRequirementFromImportFile(Object requirementJson) { + RequirementDefinition requirement = new RequirementDefinition(); + Either<RequirementDefinition, ResponseFormat> result = Either.left(requirement); + + try { + if (requirementJson instanceof String) { + String requirementJsonString = (String) requirementJson; + requirement.setCapability(requirementJsonString); + } else if (requirementJson instanceof Map) { + Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson; + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { + requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); + } + + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { + requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName())); + } + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); + Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); + if (validateAndSetOccurrencesStatus.isRight()) { + result = Either.right(validateAndSetOccurrencesStatus.right().value()); + return result; + } + if (validateAndSetOccurrencesStatus.left().value()) { + requirement.setMinOccurrences(occurrencesList.get(0).toString()); + requirement.setMaxOccurrences(occurrencesList.get(1).toString()); + } + + } + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement"); + log.debug("error when creating requirement, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private Either<Boolean, ResponseFormat> setProperties(Map<String, Object> toscaJson, Resource resource) { + Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson); + ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); + Either<Boolean, ResponseFormat> result = Either.left(true); + Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); + if (properties.isLeft()) { + List<PropertyDefinition> propertiesList = new ArrayList<>(); + Map<String, PropertyDefinition> value = properties.left().value(); + if (value != null) { + for (Entry<String, PropertyDefinition> entry : value.entrySet()) { + String name = entry.getKey(); + if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ + log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); + } + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + propertiesList.add(propertyDefinition); + } + } + resource.setProperties(propertiesList); + } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); + } + return result; + } + + private ResultStatusEnum setAttributes(Map<String, Object> toscaJson, Resource resource) { + ResultStatusEnum result = ResultStatusEnum.OK; + Either<Map<String, PropertyDefinition>, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); + if (attributes.isLeft()) { + List<PropertyDefinition> attributeList = new ArrayList<>(); + Map<String, PropertyDefinition> value = attributes.left().value(); + if (value != null) { + for (Entry<String, PropertyDefinition> entry : value.entrySet()) { + String name = entry.getKey(); + PropertyDefinition attributeDef = entry.getValue(); + attributeDef.setName(name); + attributeList.add(attributeDef); + } + } + resource.setAttributes(attributeList); + } else { + result = attributes.right().value(); + } + return result; + } + + private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource) { + Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM); + Resource derivedFromResource = null; + if (toscaDerivedFromElement.isLeft()) { + String derivedFrom = toscaDerivedFromElement.left().value(); + log.debug("Derived from TOSCA name is {}", derivedFrom); + resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom })); + Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); + + if (latestByToscaResourceName.isRight()) { + StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); + if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { + operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; + } + log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); + ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); + return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom)); + } + derivedFromResource = latestByToscaResourceName.left().value(); + } + return Either.left(derivedFromResource); + } + + private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES); + if (toscaCapabilities.isLeft()) { + Map<String, Object> jsonCapabilities = toscaCapabilities.left().value(); + Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<String, List<CapabilityDefinition>>(); + Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator(); + Set<String> capNames = new HashSet<>(); + // Getting flattened list of capabilities of parent node - cap name + // to cap type + Either<Map<String, String>, ResponseFormat> capName2Type = getCapName2Type(parentResource); + if (capName2Type.isRight()) { + ResponseFormat responseFormat = capName2Type.right().value(); + log.debug("Error during setting capabilities of imported resource: {}", responseFormat); + return Either.right(responseFormat); + } + Map<String, String> capName2TypeMap = capName2Type.left().value(); + while (capabilitiesNameValue.hasNext()) { + Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next(); + + // Validating that no req/cap duplicates exist in imported YAML + String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); + if (capNames.contains(capNameLowerCase)) { + log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase)); + } + capNames.add(capNameLowerCase); + + Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue()); + if (eitherCapability.isRight()) { + log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName()); + return Either.right(eitherCapability.right().value()); + } + + CapabilityDefinition capabilityDef = eitherCapability.left().value(); + capabilityDef.setName(capabilityNameValue.getKey()); + if (moduleCapabilities.containsKey(capabilityDef.getType())) { + moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); + } else { + List<CapabilityDefinition> list = new ArrayList<CapabilityDefinition>(); + list.add(capabilityDef); + moduleCapabilities.put(capabilityDef.getType(), list); + } + + // Validating against req/cap of "derived from" node + Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName()); + if (validateVsParentCap.isRight()) { + return Either.right(validateVsParentCap.right().value()); + } + if (!validateVsParentCap.left().value()) { + // Here parentResource is for sure not null, so it's + // null-safe + log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName()); + return Either.right(responseFormat); + } + } + if (moduleCapabilities.size() > 0) { + resource.setCapabilities(moduleCapabilities); + } + } + + return eitherResult; + + } + + private Either<Map<String, String>, ResponseFormat> getCapName2Type(Resource parentResource) { + Map<String, String> capName2type = new HashMap<>(); + if (parentResource != null) { + Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities(); + if (capabilities != null) { + for (List<CapabilityDefinition> capDefinitions : capabilities.values()) { + for (CapabilityDefinition capDefinition : capDefinitions) { + String nameLowerCase = capDefinition.getName().toLowerCase(); + if (capName2type.get(nameLowerCase) != null) { + String parentResourceName = parentResource.getName(); + log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); + BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + capName2type.put(nameLowerCase, capDefinition.getType()); + } + } + } + } + return Either.left(capName2type); + } + + private Either<Map<String, String>, ResponseFormat> getReqName2Type(Resource parentResource) { + Map<String, String> reqName2type = new HashMap<>(); + if (parentResource != null) { + Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements(); + if (requirements != null) { + for (List<RequirementDefinition> reqDefinitions : requirements.values()) { + for (RequirementDefinition reqDefinition : reqDefinitions) { + String nameLowerCase = reqDefinition.getName().toLowerCase(); + if (reqName2type.get(nameLowerCase) != null) { + String parentResourceName = parentResource.getName(); + log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); + BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + reqName2type.put(nameLowerCase, reqDefinition.getCapability()); + } + } + } + } + return Either.left(reqName2type); + } + + private Either<Boolean, ResponseFormat> validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) { + String capNameLowerCase = reqCapName.toLowerCase(); + log.trace("Validating capability {} vs parent resource", capNameLowerCase); + String parentCapType = parentCapName2Type.get(capNameLowerCase); + if (parentCapType != null) { + if (childCapabilityType.equals(parentCapType)) { + log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); + return Either.left(true); + } + Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); + if (capabilityTypeDerivedFrom.isRight()) { + log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value())); + return Either.right(responseFormat); + } + return Either.left(capabilityTypeDerivedFrom.left().value()); + } + return Either.left(true); + } + + private Either<CapabilityDefinition, ResponseFormat> createCapabilityFromImportFile(Object capabilityJson) { + + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + Either<CapabilityDefinition, ResponseFormat> result = Either.left(capabilityDefinition); + + try { + if (capabilityJson instanceof String) { + String capabilityJsonString = (String) capabilityJson; + capabilityDefinition.setType(capabilityJsonString); + } else if (capabilityJson instanceof Map) { + Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson; + // Type + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); + } + // ValidSourceTypes + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { + capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())); + } + // ValidSourceTypes + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); + } + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); + Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); + if (validateAndSetOccurrencesStatus.isRight()) { + result = Either.right(validateAndSetOccurrencesStatus.right().value()); + return result; + } + if (validateAndSetOccurrencesStatus.left().value()) { + capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); + capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); + } + } + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + + Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); + if (propertiesRes.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); + return result; + } else { + propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); + List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); + capabilityDefinition.setProperties(capabilityProperties); + } + } + } else if (!(capabilityJson instanceof List)) { + + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); + log.debug("error when creating capability, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { + String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : ""; + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName); + + log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e); + ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); + auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative); + return errorResponseWrapper; + } + + private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { +// EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus()); +// String message = ""; +// if (errorResponseWrapper.getMessageId() != null) { +// message = errorResponseWrapper.getMessageId() + ": "; +// } +// message += errorResponseWrapper.getFormattedMessage(); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); + + String version, lifeCycleState; + if (isNormative) { + version = Constants.FIRST_CERTIFIED_VERSION_VERSION; + lifeCycleState = LifecycleStateEnum.CERTIFIED.name(); + } else { + version = ""; + lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); + + } +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); +// getAuditingManager().auditEvent(auditingFields); + + + String message = ""; + if (errorResponseWrapper.getMessageId() != null) { + message = errorResponseWrapper.getMessageId() + ": "; + } + message += errorResponseWrapper.getFormattedMessage(); + + + + AuditEventFactory factory = new AuditImportResourceAdminEventFactory( + CommonAuditData.newBuilder() + .status(errorResponseWrapper.getStatus()) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + ResourceAuditData.newBuilder() + .state(lifeCycleState) + .version(version) + .build(), + ResourceAuditData.newBuilder() + .state("") + .version("") + .build(), + ComponentTypeEnum.RESOURCE.getValue(), resourceMetaData.getName(), "", user, ""); + getAuditingManager().auditEvent(factory); + + } + + private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) { + this.populateResourceMetadata(resourceMetaData, resource); + resource.setCreatorUserId(resourceMetaData.getContactId()); + List<CategoryDefinition> categories = resourceMetaData.getCategories(); + calculateResourceIsAbstract(resource, categories); + } + + private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) { + if (categories != null && !categories.isEmpty()) { + CategoryDefinition categoryDef = categories.get(0); + resource.setAbstract(false); + if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) { + SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); + if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) { + resource.setAbstract(true); + } + } + } + } + + private void setConstantMetaData(Resource resource, boolean shouldBeCertified) { + String version; + LifecycleStateEnum state; + if(shouldBeCertified){ + version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; + }else{ + version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; + } + resource.setVersion(version); + resource.setLifecycleState(state); + resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); + resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); + + } + + private Either<Boolean, ResponseFormat> validateOccurrences(List<Object> occurrensesList) { + + if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { + log.debug("Occurrenses list empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (occurrensesList.size() < 2) { + log.debug("Occurrenses list size not 2"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + Object minObj = occurrensesList.get(0); + Object maxObj = occurrensesList.get(1); + Integer minOccurrences = null; + Integer maxOccurrences = null; + if (minObj instanceof Integer) + minOccurrences = (Integer) minObj; + else { + log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + if (minOccurrences < 0) { + log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (maxObj instanceof String) { + if ("UNBOUNDED".equals(maxObj)) { + return Either.left(true); + } else { + log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + } else { + if (maxObj instanceof Integer) + maxOccurrences = (Integer) maxObj; + else { + log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { + log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + } + + return Either.left(true); + + } + + public synchronized void init(ServletContext servletContext) { + if (this.servletContext == null) { + this.servletContext = servletContext; + responseFormatManager = ResponseFormatManager.getInstance(); + resourceBusinessLogic = getResourceBL(servletContext); + } + } + + public boolean isResourceExist(String resourceName) { + return resourceBusinessLogic.isResourceExist(resourceName); + } + + private ResourceBusinessLogic getResourceBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class); + return resourceBl; + } + + public ServletContext getServletContext() { + return servletContext; + } + + public AuditingManager getAuditingManager() { + return auditingManager; + } + + public ResponseFormatManager getResponseFormatManager() { + return responseFormatManager; + } + + public void setResponseFormatManager(ResponseFormatManager responseFormatManager) { + this.responseFormatManager = responseFormatManager; + } + + public ResourceBusinessLogic getResourceBusinessLogic() { + return resourceBusinessLogic; + } + + public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) { + this.resourceBusinessLogic = resourceBusinessLogic; + } + + public Logger getLog() { + return log; + } + + public IGraphLockOperation getGraphLockOperation() { + return graphLockOperation; + } + + public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { + this.graphLockOperation = graphLockOperation; + } + + public void setServletContext(ServletContext servletContext) { + this.servletContext = servletContext; + } + + public void setAuditingManager(AuditingManager auditingManager) { + this.auditingManager = auditingManager; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java index 136121484d..a6344929a5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java @@ -34,44 +34,44 @@ import org.slf4j.LoggerFactory; public class ResponseFormatManager { - private volatile static ResponseFormatManager instance; - private static ConfigurationManager configurationManager; - private static Logger log = LoggerFactory.getLogger(ResponseFormatManager.class.getName()); + private volatile static ResponseFormatManager instance; + private static ConfigurationManager configurationManager; + private static final Logger log = LoggerFactory.getLogger(ResponseFormatManager.class); - public static ResponseFormatManager getInstance() { - if (instance == null) { + public static ResponseFormatManager getInstance() { + if (instance == null) { - instance = init(); - } - return instance; - } + instance = init(); + } + return instance; + } - private static synchronized ResponseFormatManager init() { - if (instance == null) { - instance = new ResponseFormatManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } + private static synchronized ResponseFormatManager init() { + if (instance == null) { + instance = new ResponseFormatManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } - public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) { - ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration(); - ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name()); - if (errorInfo == null) { - log.debug("failed to locate {} in error configuration", responseEnum.name()); - errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name()); - } - ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode()); - String errorMessage = errorInfo.getMessage(); - String errorMessageId = errorInfo.getMessageId(); - ErrorInfoType errorInfoType = errorInfo.getErrorInfoType(); - if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) { - errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) { - errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.OK)) { - errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables)); - } - return errorResponseWrapper; - } + public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) { + ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration(); + ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name()); + if (errorInfo == null) { + log.debug("failed to locate {} in error configuration", responseEnum); + errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name()); + } + ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode()); + String errorMessage = errorInfo.getMessage(); + String errorMessageId = errorInfo.getMessageId(); + ErrorInfoType errorInfoType = errorInfo.getErrorInfoType(); + if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) { + errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables)); + } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) { + errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables)); + } else if (errorInfoType.equals(ErrorInfoType.OK)) { + errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables)); + } + return errorResponseWrapper; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 23852c30a2..14db1408b7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +20,33 @@ package org.openecomp.sdc.be.components.impl; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - +import com.google.common.base.Strings; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.distribution.engine.INotificationData; import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datamodel.ServiceRelations; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -67,6 +61,8 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -79,12 +75,12 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; import org.openecomp.sdc.common.util.GeneralUtility; @@ -96,1997 +92,2213 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("serviceBusinessLogic") public class ServiceBusinessLogic extends ComponentBusinessLogic { - private static final String STATUS_SUCCESS_200 = "200"; - - private static final String STATUS_DEPLOYED = "DEPLOYED"; - - @Autowired - private IElementOperation elementDao; - - @Autowired - private IDistributionEngine distributionEngine; - - // @Autowired - // private AuditingDao auditingDao; - - @Autowired - private AuditCassandraDao auditCassandraDao; - - @Autowired - private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic; - - @Autowired - private GroupBusinessLogic groupBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName()); - private static final String INITIAL_VERSION = "0.1"; - - public ServiceBusinessLogic() { - log.debug("ServiceBusinessLogic started"); - } - - public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) { - - Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.debug("check request state"); - Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user); - if (validateEnum.isRight()) { - return Either.right(validateEnum.right().value()); - } - DistributionTransitionEnum distributionTransition = validateEnum.left().value(); - AuditingActionEnum auditAction = (distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT); - Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction); - if (commentResponse.isRight()) { - return Either.right(commentResponse.right().value()); - } - String comment = commentResponse.left().value(); - - Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment); - if (validateService.isRight()) { - return Either.right(validateService.right().value()); - } - Service service = validateService.left().value(); - DistributionStatusEnum initState = service.getDistributionStatus(); - - Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment); - if (validateUser.isRight()) { - return Either.right(validateUser.right().value()); - } - user = validateUser.left().value(); - - // lock resource - /* - * StorageOperationStatus lockResult = graphLockOperation.lockComponent(serviceId, NodeTypeEnum.Service); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. - * BeFailedLockObjectError, "ChangeServiceDistributionState"); log.debug("Failed to lock service {} error - {}", serviceId, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, - * service.getVersion(), service.getServiceName()); - * - * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); } - */ - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - - try { - - DistributionStatusEnum newState; - if (distributionTransition == DistributionTransitionEnum.APPROVE) { - newState = DistributionStatusEnum.DISTRIBUTION_APPROVED; - } else { - newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; - } - Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState); - if (result.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); - log.debug("service {} is change destribuation status failed", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - Service updatedService = result.left().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, updatedService.getDistributionStatus().name()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, initState.name()); - createAudit(user, auditAction, comment, updatedService, responseFormat, auditingFields); - return Either.left(result.left().value()); - - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - - } - - public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<List<Map<String, Object>>, ActionStatus> result; - try { - - // Certified Version - if (componentVersion.endsWith(".0")) { - Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID); - if (eitherAuditingForCertified.isLeft()) { - result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value())); - } else { - result = Either.right(eitherAuditingForCertified.right().value()); - } - } - // Uncertified Version - else { - result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion); - } - } catch (Exception e) { - log.debug("get Audit Records failed with exception {}", e); - result = Either.right(ActionStatus.GENERAL_ERROR); - } - - if (result.isRight()) { - return Either.right(componentsUtils.getResponseFormat(result.right().value())); - } else { - return Either.left(result.left().value()); - } - - } - - private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) { - // First Query - Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); - - if (eitherprevVerAudit.isRight()) { - return Either.right(eitherprevVerAudit.right().value()); - } - - // Second Query - Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); - if (eitherCurrVerAudit.isRight()) { - return Either.right(eitherCurrVerAudit.right().value()); - } - - List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value()); - List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value()); - - List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>(); - duplicateElements.addAll(prevVerAuditList); - duplicateElements.retainAll(currVerAuditList); - - List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>(); - joinedNonDuplicatedList.addAll(prevVerAuditList); - joinedNonDuplicatedList.removeAll(duplicateElements); - joinedNonDuplicatedList.addAll(currVerAuditList); - - return Either.left(joinedNonDuplicatedList); - } - - private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) { - - List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>(); - for (AuditingGenericEvent auditEvent : prevVerAuditList) { - auditEvent.fillFields(); - prevVerAudit.add(auditEvent.getFields()); - } - return prevVerAudit; - } - - /** - * createService - * - * @param service - * - Service - * @param user - * - modifier data (userId) - * @return Either<Service, responseFormat> - */ - public Either<Service, ResponseFormat> createService(Service service, User user) { - - // get user details - Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - service.setCreatorUserId(user.getUserId()); - - // warn on overridden fields - checkFieldsForOverideAttampt(service); - // enrich object - log.debug("enrich service with version and state"); - service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - service.setVersion(INITIAL_VERSION); - service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); - service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); - if (createServiceResponse.isRight()) { - return createServiceResponse; - } - return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); - } - - private void checkFieldsForOverideAttampt(Service service) { - checkComponentFieldsForOverrideAttempt(service); - if ((service.getDistributionStatus() != null)) { - log.info("Distribution Status cannot be defined by user. This field will be overridden by the application"); - } - } - - private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) { - log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult); - - try { - - createMandatoryArtifactsData(service, user); - createServiceApiArtifactsData(service, user); - setToscaArtifactsPlaceHolders(service, user); - Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service); - if (genericServiceEither.isRight()) - return Either.right(genericServiceEither.right().value()); - - generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); - - Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service); - - // service created successfully!!! - if (dataModelResponse.isLeft()) { - log.debug("Service created successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - ASDCKpiApi.countCreatedServicesKPI(); - return Either.left(dataModelResponse.left().value()); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE); - log.debug("audit before sending response"); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - - } finally { - graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service); - } - } - - @SuppressWarnings("unchecked") - private void createServiceApiArtifactsData(Service service, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String serviceUniqueId = - // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion()); - String serviceUniqueId = service.getUniqueId(); - Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts(); - if (artifactMap == null) - artifactMap = new HashMap<String, ArtifactDefinition>(); - - Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts(); - List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); - - List<CategoryDefinition> categories = service.getCategories(); - boolean isCreateArtifact = true; - if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { - for (String exlude : exludeServiceCategory) { - if (exlude.equalsIgnoreCase(categories.get(0).getName())) { - isCreateArtifact = false; - break; - } - } - - } - - if (serviceApiArtifacts != null && isCreateArtifact) { - Set<String> keys = serviceApiArtifacts.keySet(); - for (String serviceApiArtifactName : keys) { - Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName); - ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true); - artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - - service.setServiceApiArtifacts(artifactMap); - } - } - - private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { - - Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum); - if (validationResponse.isRight()) { - return Either.right(validationResponse.right().value()); - } - service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - service.setContactId(service.getContactId().toLowerCase()); - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - service.setInvariantUUID(invariantUUID); - - return Either.left(service); - } - - private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { - Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum); - if (componentsFieldsValidation.isRight()) { - return componentsFieldsValidation; - } - - log.debug("validate service name uniqueness"); - Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum); - if (serviceNameUniquenessValidation.isRight()) { - return serviceNameUniquenessValidation; - } - - log.debug("validate category"); - Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum); - if (categoryValidation.isRight()) { - return categoryValidation; - } - - // validate project name (ProjectCode) - mandatory in service - log.debug("validate projectName"); - Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; - } - - log.debug("validate service type"); - Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum); - if (serviceTypeValidation.isRight()) { - return serviceTypeValidation; - } - - log.debug("validate service role"); - Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum); - if (serviceRoleValidation.isRight()) { - return serviceRoleValidation; - } - - return Either.left(true); - - } - - private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) { - log.debug("validate Service category"); - - if (service.getCategories() == null || service.getCategories().size() == 0) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - - Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories()); - if (validatCategory.isRight()) { - ResponseFormat responseFormat = validatCategory.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - return Either.left(true); - } - - public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); - - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map<String, Boolean> result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - public void setElementDao(IElementOperation elementDao) { - this.elementDao = elementDao; - } - - public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { - this.auditCassandraDao = auditingDao; - } - - /* - * public void setUserAdmin(UserAdminBuisinessLogic userAdmin) { this.userAdmin = userAdmin; } - * - * public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; } - * - * public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; } - */ - - public ArtifactsBusinessLogic getArtifactBl() { - return artifactsBusinessLogic; - } - - public void setArtifactBl(ArtifactsBusinessLogic artifactBl) { - this.artifactsBusinessLogic = artifactBl; - } - - public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) { - Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<Role>(), null, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); - } - - Service currentService = storageStatus.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) { - log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate); - if (validationRsponse.isRight()) { - log.info("service update metadata: validations field."); - return validationRsponse; - } - Service serviceToUpdate = validationRsponse.left().value(); - // lock resource - - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); - if (updateResponse.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); - log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - return Either.left(updateResponse.left().value()); - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion()); - Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String creatorUserIdUpdated = serviceUpdate.getCreatorUserId(); - String creatorUserIdCurrent = currentService.getCreatorUserId(); - if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) { - log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated); - } - - String creatorFullNameUpdated = serviceUpdate.getCreatorFullName(); - String creatorFullNameCurrent = currentService.getCreatorFullName(); - if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) { - log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated); - } - - String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId(); - String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId(); - if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) { - log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated); - } - - String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName(); - String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName(); - if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) { - log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated); - } - - response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus(); - DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus(); - if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals((distributionStatusCurrent != null ? distributionStatusCurrent.name() : null))) { - log.info("update srvice: recived request to update distributionStatus to {} the field is not updatable ignoring.", distributionStatusUpdated); - } - - if (serviceUpdate.getProjectCode() != null) { - response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - } - - response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - Long creationDateUpdated = serviceUpdate.getCreationDate(); - Long creationDateCurrent = currentService.getCreationDate(); - if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) { - log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated); - } - - String versionUpdated = serviceUpdate.getVersion(); - String versionCurrent = currentService.getVersion(); - if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { - log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); - } - - response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateContactId(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate(); - Long lastUpdateDateCurrent = currentService.getLastUpdateDate(); - if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) { - log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated); - } - - LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState(); - LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState(); - if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) { - log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated); - } - - Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion(); - Boolean isHighestVersionCurrent = currentService.isHighestVersion(); - if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) { - log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated); - } - - String uuidUpdated = serviceUpdate.getUUID(); - String uuidCurrent = currentService.getUUID(); - if (!uuidCurrent.equals(uuidUpdated)) { - log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); - } - - response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String currentInvariantUuid = currentService.getInvariantUUID(); - String updatedInvariantUuid = serviceUpdate.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Product invariant UUID is automatically set and cannot be updated"); - serviceUpdate.setInvariantUUID(currentInvariantUuid); - } - validateAndUpdateEcompNaming(currentService, serviceUpdate); - - currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); - - return Either.left(currentService); - - } - - private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) { - Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming(); - Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming(); - if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) { - currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate); - } - String namingPolicyUpd = serviceUpdate.getNamingPolicy(); - if (!currentService.isEcompGeneratedNaming()) { - if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) { - log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false"); - currentService.setNamingPolicy(""); - } else { - currentService.setNamingPolicy(namingPolicyUpd); - } - }else{ - currentService.setNamingPolicy(namingPolicyUpd); - } - } - - private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { - String contactIdUpdated = serviceUpdate.getContactId(); - String contactIdCurrent = currentService.getContactId(); - if (!contactIdCurrent.equals(contactIdUpdated)) { - Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction); - if (validatContactId.isRight()) { - ResponseFormat errorRespons = validatContactId.right().value(); - return Either.right(errorRespons); - } - currentService.setContactId(contactIdUpdated.toLowerCase()); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - List<String> tagsUpdated = serviceUpdate.getTags(); - List<String> tagsCurrent = currentService.getTags(); - if (tagsUpdated == null || tagsUpdated.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS); - componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, "", "", audatingAction, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setTags(tagsUpdated); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - String descriptionUpdated = serviceUpdate.getDescription(); - String descriptionCurrent = currentService.getDescription(); - if (!descriptionCurrent.equals(descriptionUpdated)) { - Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction); - if (validateDescriptionResponse.isRight()) { - ResponseFormat errorRespons = validateDescriptionResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setDescription(serviceUpdate.getDescription()); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { - String projectCodeUpdated = serviceUpdate.getProjectCode(); - String projectCodeCurrent = currentService.getProjectCode(); - if (!projectCodeCurrent.equals(projectCodeUpdated)) { - - Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setProjectCode(projectCodeUpdated); - - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - String iconUpdated = serviceUpdate.getIcon(); - String iconCurrent = currentService.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction); - if (validatIconResponse.isRight()) { - ResponseFormat errorRespons = validatIconResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setIcon(iconUpdated); - } else { - log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) { - String serviceNameUpdated = serviceUpdate.getName(); - String serviceNameCurrent = currentService.getName(); - if (!serviceNameCurrent.equals(serviceNameUpdated)) { - if (!hasBeenCertified) { - Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction); - if (validatServiceNameResponse.isRight()) { - ResponseFormat errorRespons = validatServiceNameResponse.right().value(); - return Either.right(errorRespons); - } - - Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction); - if (serviceNameUniquenessValidation.isRight()) { - return serviceNameUniquenessValidation; - } - currentService.setName(serviceNameUpdated); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated)); - - } else { - log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { - String updatedServiceType = updatedService.getServiceType(); - String currentServiceType = currentService.getServiceType(); - if (!currentServiceType.equals(updatedServiceType)) { - Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction); - if (validateServiceType.isRight()) { - ResponseFormat errorResponse = validateServiceType.right().value(); - componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - currentService.setServiceType(updatedServiceType); - } - return Either.left(true); - } - - protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - String serviceType = ((Service)component).getServiceType(); - if (serviceType != null){ - serviceType = cleanUpText(serviceType); - Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType); - if (validateServiceType.isRight()) { - ResponseFormat responseFormat = validateServiceType.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } else { - return Either.left(false); - } - } - - - private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) { - if (serviceType.equals("")){ - return Either.left(true); - } else { - if (!ValidationUtils.validateServiceTypeLength(serviceType)) { - log.info("service type exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateIsEnglish(serviceType)) { - log.info("service type is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { - String updatedServiceRole = updatedService.getServiceRole(); - String currentServiceRole = currentService.getServiceRole(); - if (!currentServiceRole.equals(updatedServiceRole)) { - Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction); - if (validateServiceRole.isRight()) { - ResponseFormat errorResponse = validateServiceRole.right().value(); - componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - currentService.setServiceRole(updatedServiceRole); - } - return Either.left(true); - } - - protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - String serviceRole = ((Service)component).getServiceRole(); - if (serviceRole != null){ - serviceRole = cleanUpText(serviceRole); - - Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole); - if (validateServiceRole.isRight()) { - ResponseFormat responseFormat = validateServiceRole.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } else { - return Either.left(false); - } - } - - - private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) { - if (serviceRole.equals("")){ - return Either.left(true); - } else { - if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { - log.info("service role exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateIsEnglish(serviceRole)) { - log.info("service role is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - - - private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories(); - List<CategoryDefinition> categoryCurrent = currentService.getCategories(); - Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction); - if (validatCategoryResponse.isRight()) { - ResponseFormat errorRespons = validatCategoryResponse.right().value(); - return Either.right(errorRespons); - } - if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { - if (!hasBeenCertified) { - currentService.setCategories(categoryUpdated); - } else { - log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - - } - - public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) { - if (list != null) { - if (list.size() > 1) { - log.debug("Must be only one category for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - CategoryDefinition category = list.get(0); - if (category.getSubcategories() != null) { - log.debug("Subcategories cannot be defined for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY); - return Either.right(responseFormat); - } - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - - log.debug("validating service category {} against valid categories list", list); - Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories(); - if (categorys.isRight()) { - log.debug("failed to retrive service categories from Titan"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); - return Either.right(responseFormat); - } - List<CategoryDefinition> categoryList = categorys.left().value(); - for (CategoryDefinition value : categoryList) { - if (value.getName().equals(category.getName())) { - return Either.left(true); - } - } - log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); - } - return Either.left(false); - } - - public ResponseFormat deleteService(String serviceId, User user) { - ResponseFormat responseFormat; - String ecompErrorContext = "delete service"; - - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - user = eitherCreator.left().value(); - - Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId); - if (serviceStatus.isRight()) { - log.debug("failed to get service {}", serviceId); - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), ""); - } - - Service service = serviceStatus.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - - result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) { - ResponseFormat responseFormat; - String ecompErrorContext = "delete service"; - Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return validateEmptyResult.right().value(); - } - - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - user = eitherCreator.left().value(); - - Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); - if (getResult.isRight()) { - return getResult.right().value(); - } - Service service = getResult.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } - } - - public Either<Service, ResponseFormat> getService(String serviceId, User user) { - String ecompErrorContext = "Get service"; - Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - log.debug("failed to get service by id {}", serviceId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId)); - } - - if(!(storageStatus.left().value() instanceof Service)){ - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId)); - } - Service service = storageStatus.left().value(); - return Either.left(service); - - - - - } - - public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) { - Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); - if (storageStatus.isRight()) { - log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName)); - } - Service service = storageStatus.left().value(); - return Either.left(service); - } - - @SuppressWarnings("unchecked") - private void createMandatoryArtifactsData(Service service, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String serviceUniqueId = - // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion()); - String serviceUniqueId = service.getUniqueId(); - Map<String, ArtifactDefinition> artifactMap = service.getArtifacts(); - if (artifactMap == null) - artifactMap = new HashMap<String, ArtifactDefinition>(); - - Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts(); - List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); - - String category = service.getCategories().get(0).getName(); - boolean isCreateArtifact = true; - if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { - for (String exlude : exludeServiceCategory) { - if (exlude.equalsIgnoreCase(category)) { - isCreateArtifact = false; - break; - } - } - - } - - if (informationalServiceArtifacts != null && isCreateArtifact) { - Set<String> keys = informationalServiceArtifacts.keySet(); - for (String informationalServiceArtifactName : keys) { - Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName); - ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - } - - service.setArtifacts(artifactMap); - } - } - - private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) { - - ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); - - if (isServiceApi) { - artifactInfo.setMandatory(false); - artifactInfo.setServiceApi(true); - } - return artifactInfo; - } - - private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) { - DistributionTransitionEnum transitionEnum = null; - - transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); - if (transitionEnum == null) { - BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution"); - log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); - ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(error); - } - - return Either.left(transitionEnum); - } - - private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) { - String data = comment.getUserRemarks(); - - if (data == null || data.trim().isEmpty()) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); - log.debug("user comment cannot be empty or null."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - data = ValidationUtils.removeNoneUtf8Chars(data); - data = ValidationUtils.removeHtmlTags(data); - data = ValidationUtils.normaliseWhitespace(data); - data = ValidationUtils.stripOctets(data); - - if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); - log.debug("user comment exceeds limit."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); - } - if (!ValidationUtils.validateIsEnglish(data)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(data); - } - - private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); - createAudit(user, auditAction, comment, responseFormat); - return Either.right(responseFormat); - } - Service service = storageStatus.left().value(); - - if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { - log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - return Either.left(service); - } - - private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { - log.debug("get user from DB"); - - // get user details - Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - List<Role> roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.GOVERNOR); - roles.add(Role.OPS); - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - return Either.left(user); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, ResponseFormat responseFormat) { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - - createAudit(user, auditAction, comment, null, responseFormat, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, component.getDistributionStatus().name()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, component.getDistributionStatus().name()); - createAudit(user, auditAction, comment, component, component.getLifecycleState().name(), component.getVersion(), responseFormat, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - log.debug("audit before sending response"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - componentsUtils.auditComponent(responseFormat, user, component, null, null, auditAction, ComponentTypeEnum.SERVICE, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, String prevState, String prevVersion, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - log.debug("audit before sending response"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - componentsUtils.auditComponent(responseFormat, user, component, prevState, prevVersion, auditAction, ComponentTypeEnum.SERVICE, auditingFields); - } - - public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { - - Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - User user = eitherCreator.left().value(); - - Either<Service, ResponseFormat> result = null; - ResponseFormat response = null; - Service updatedService = null; - String did = ThreadLocalsHolder.getUuid(); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did); - // DE194021 - String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); - if (configuredEnvName != null && false == envName.equals(configuredEnvName)) { - log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName); - envName = configuredEnvName; - } - // DE194021 - - ServletContext servletContext = request.getSession().getServletContext(); - boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE - if (!isDistributionEngineUp) { - BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN"); - log.debug("Distribution Engine is DOWN"); - response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(response); - } - - Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId); - if (serviceRes.isRight()) { - log.debug("failed retrieving service"); - response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); - componentsUtils.auditComponent(response, user, null, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields); - return Either.right(response); - } - Service service = serviceRes.left().value(); - String dcurrStatus = service.getDistributionStatus().name(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, dcurrStatus); - - Either<INotificationData, StorageOperationStatus> readyForDistribution = distributionEngine.isReadyForDistribution(service, did, envName); - if (readyForDistribution.isLeft()) { - INotificationData notificationData = readyForDistribution.left().value(); - StorageOperationStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName()); - if (notifyServiceResponse == StorageOperationStatus.OK) { - Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED); - if (updateStateRes.isLeft() && updateStateRes.left().value() != null) { - updatedService = updateStateRes.left().value(); - dcurrStatus = updatedService.getDistributionStatus().name(); - } else { - // The response is not relevant - updatedService = service; - } - ASDCKpiApi.countActivatedDistribution(); - response = componentsUtils.getResponseFormat(ActionStatus.OK); - result = Either.left(updatedService); - } else { - BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); - log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); - response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - result = Either.right(response); - } - } else { - StorageOperationStatus distEngineValidationResponse = readyForDistribution.right().value(); - response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(distEngineValidationResponse), service.getName(), envName); - result = Either.right(response); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, dcurrStatus); - componentsUtils.auditComponent(response, user, service, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields); - return result; - } - - // convert to private after deletion of temp url - public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { - - Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - String serviceId = service.getUniqueId(); - Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state); - if (result.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); - log.debug("service {} change distribution status failed", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - return Either.left(result.left().value()); - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) { - - Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.debug("mark distribution deployed"); - - AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; - Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId); - if (getServiceResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId); - log.debug("service {} not found", serviceId); - ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); - - return Either.right(responseFormat); - } - - Service service = getServiceResponse.left().value(); - - Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service); - if (validateRoleForDeploy.isRight()) { - return Either.right(validateRoleForDeploy.right().value()); - } - user = validateRoleForDeploy.left().value(); - - return checkDistributionAndDeploy(did, user, auditAction, service); - - } - - public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) { - Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri -> - // Only one VF Module Artifact per instance - add it to a list of one - buildArtifactGenList(service, modifier, shouldLock, ri); - - return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); - - } - - private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) { - List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>(); - - if (ri.getOriginType() == OriginTypeEnum.VF) { - asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock)); - } - return asList; - } - - private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) { - - return currVF.getGroupInstances(); - } - - private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) { - ArtifactDefinition vfModuleAertifact = null; - if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { - Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); - if (optionalVfModuleArtifact.isPresent()) { - vfModuleAertifact = optionalVfModuleArtifact.get(); - } - } - if (vfModuleAertifact == null) { - Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement()); - if (createVfModuleArtifact.isLeft()) { - vfModuleAertifact = createVfModuleArtifact.left().value(); - } else { - responseWrapper.setInnerElement(createVfModuleArtifact.right().value()); - } - } - return vfModuleAertifact; - } - - private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper) { - // Converts GroupDefinition to VfModuleArtifactPayload which is the - // format used in the payload - - // List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList()); - List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>(); - if (groupsForCurrVF != null) { - for (GroupInstance groupInstance : groupsForCurrVF) { - VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance); - vfModulePayloadForCurrVF.add(modulePayload); - } - Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); - // Update Payload With Heat Env -// vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); - - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); - payloadWrapper.setInnerElement(vfModulePayloadString); - } - - } - - private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) { - ArtifactDefinition vfModuleAertifact = null; - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - Wrapper<String> payloadWrapper = new Wrapper<>(); - List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); - if (responseWrapper.isEmpty()) { - fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper); - } - if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { - vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); - } - if (responseWrapper.isEmpty() && vfModuleAertifact != null) { - vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service); - } - - Either<ArtifactDefinition, ResponseFormat> result; - if (responseWrapper.isEmpty()) { - result = Either.left(vfModuleAertifact); - } else { - result = Either.right(responseWrapper.getInnerElement()); - } - - return result; - } - - private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) { - ArtifactDefinition result = null; -// final Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); -// if (eitherResource.isRight()) { -// responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); -// } else if (!payloadWrapper.isEmpty()) { -// Resource resource = eitherResource.left().value(); - Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), - () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); - if (eitherPayload.isLeft()) { - result = eitherPayload.left().value(); - } else { - responseWrapper.setInnerElement(eitherPayload.right().value()); - } -// } - if (result == null) { - result = vfModuleArtifact; - } - - return result; - } - - private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) { - - ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition(); - String newCheckSum = null; - - vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact"); - vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata"); - vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType()); - vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata"); - vfModuleArtifactDefinition.setTimeout(0); - vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json"); - vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString); - if (vfModulePayloadString != null) { - newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes()); - } - vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); - - Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); - - Either<ArtifactDefinition, ResponseFormat> result; - if (addArifactToComponent.isLeft()) { - result = Either.left(addArifactToComponent.left().value()); - } else { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value()))); - } - - return result; - } - - public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock) { - - Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance -> - // Get All Deployment Artifacts - service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()). - // Filter in Only Heat Env - filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())). - // Create ArtifactGenerator from those Artifacts - map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList()); - - return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); - - } - - private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) { - - // Get Flat List of (Callable) ArtifactGenerator for all the RI in the - // service - if (service.getComponentInstances() != null) { - List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); - if (artifactGenList != null && !artifactGenList.isEmpty()) { - for (ArtifactGenerator<CallVal> entry : artifactGenList) { - Either<CallVal, ResponseFormat> callRes; - try { - callRes = entry.call(); - if (callRes.isRight()) { - log.debug("Failed to generate artifact error : {}", callRes.right().value()); - return Either.right(callRes.right().value()); - } - } catch (Exception e) { - log.debug("Failed to generate artifact exception : {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } - } - return Either.left(service); - } - - abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> { - - } - - class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> { - ArtifactDefinition artifactDefinition; - Service service; - String resourceInstanceName; - User modifier; - String instanceId; - boolean shouldLock; - - HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) { - this.artifactDefinition = artifactDefinition; - this.service = service; - this.resourceInstanceName = resourceInstanceName; - this.modifier = modifier; - this.shouldLock = shouldLock; - this.instanceId = instanceId; - } - - @Override - public Either<ArtifactDefinition, ResponseFormat> call() throws Exception { - return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId); - } - - public ArtifactDefinition getArtifactDefinition() { - return artifactDefinition; - } - - } - - class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> { - private User user; - private ComponentInstance componentInstance; - private Service service; - boolean shouldLock; - - @Override - public Either<ArtifactDefinition, ResponseFormat> call() throws Exception { - return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock); - } - - private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) { - super(); - this.user = user; - this.componentInstance = componentInstance; - this.service = service; - this.shouldLock = shouldLock; - } - - } - - private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { - boolean isDeployed = isDistributionDeployed(did, service); - if (isDeployed) { - return Either.left(service); - } - Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service); - if (distributionSuccess.isRight()) { - return Either.right(distributionSuccess.right().value()); - } - - log.debug("mark distribution {} as deployed - success", did); - componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user); - return Either.left(service); - } - - private boolean isDistributionDeployed(String did, Service service) { - Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); - - boolean isDeployed = false; - if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) { - // already deployed - log.debug("distribution {} is already deployed", did); - isDeployed = true; - } - return isDeployed; - } - - protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) { - - log.trace("checkDistributionSuccess"); - // get all "DRequest" records for this distribution - // Either<List<ESTimeBasedEvent>, ActionStatus> distRequestsResponse = - // auditingDao.getListOfDistributionByAction(did, - // AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), "", - // ResourceAdminEvent.class); - Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); - if (distRequestsResponse.isRight()) { - ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value()); - return Either.right(error); - } - - List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value(); - if (distributionRequests.isEmpty()) { - BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did); - log.info("distribution {} is not found", did); - ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND); - return Either.right(error); - } - boolean isRequestSucceeded = false; - for (ResourceAdminEvent event : distributionRequests) { - String eventStatus = event.getStatus(); - if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { - isRequestSucceeded = true; - break; - } - } - - // get all "DNotify" records for this distribution - // Either<List<ESTimeBasedEvent>, ActionStatus> - // distNotificationsResponse = - // auditingDao.getListOfDistributionByAction(did, - // AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), "", - // DistributionNotificationEvent.class); - Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); - if (distNotificationsResponse.isRight()) { - ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value()); - return Either.right(error); - } - - List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value(); - boolean isNotificationsSucceeded = false; - for (DistributionNotificationEvent event : distributionNotifications) { - String eventStatus = event.getStatus(); - if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { - isNotificationsSucceeded = true; - break; - } - } - - // if request failed OR there are notifications that failed - if (!(isRequestSucceeded && isNotificationsSucceeded)) { - - log.info("distribution {} has failed", did); - ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); - auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); - return Either.right(error); - } - return Either.left(true); - } - - private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) { - - ResponseFormat error = componentsUtils.getResponseFormat(status, params); - String message = ""; - if (error.getMessageId() != null) { - message = error.getMessageId() + ": "; - } - message += error.getFormattedMessage(); - - if (service != null) { - componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user); - } else { - componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user); - } - return error; - } - - private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); - log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); - auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); - return Either.right(responseFormat); - } - user = eitherCreator.left().value(); - log.debug("validate user role"); - List<Role> roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.OPS); - Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null); - if (validateRes.isRight()) { - log.info("role {} is not allowed to perform this action", user.getRole()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - return Either.left(user); - - } - - @Override - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - - } - - @Override - public Either<List<String>, ResponseFormat> deleteMarkedComponents() { - return deleteMarkedComponents(ComponentTypeEnum.SERVICE); - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return serviceComponentInstanceBusinessLogic; - } - - @Override - public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - - Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - if (getComponentRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); - return Either.right(responseFormat); - } - - List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances(); - // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList()); - - return Either.left(componentInstances); - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - /** - * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date - * - * @param modifier - * @param serviceId - * @param componentInstanceId - * @param groupInstanceId - * @param newProperties - * @return - */ - public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) { - - Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null; - Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes; - Component component = null; - Either<Boolean, ResponseFormat> lockResult = null; - log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId); - try { - validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier); - if (validateUserAndComponentRes.isRight()) { - log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId); - actionResult = Either.right(validateUserAndComponentRes.right().value()); - } - if (actionResult == null) { - component = validateUserAndComponentRes.left().value().getKey(); - lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service"); - if (lockResult.isRight()) { - log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage()); - actionResult = Either.right(lockResult.right().value()); - } else { - log.debug("The service with system name {} locked. ", component.getSystemName()); - } - } - if (actionResult == null) { - actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); - if (actionResult.isRight()) { - log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage()); - } - } - } catch (Exception e) { - log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service); - } - } - return actionResult; - } - - private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) { - - Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null; - Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; - Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes; - ComponentInstance relatedComponentInstance = null; - GroupInstance oldGroupInstance = null; - Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null; - GroupInstance updatedGroupInstance = null; - boolean inTransaction = true; - boolean shouldCloseTransaction = true; - findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId); - if (findGroupInstanceRes.isRight()) { - log.debug("Group instance {} not found. ", groupInstanceId); - actionResult = Either.right(findGroupInstanceRes.right().value()); - } - if (actionResult == null) { - oldGroupInstance = findGroupInstanceRes.left().value().getValue(); - relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); - updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction); - if (updateGroupInstanceResult.isRight()) { - log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(updateGroupInstanceResult.right().value()); - } - } - if (actionResult == null) { - updatedGroupInstance = updateGroupInstanceResult.left().value(); - if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) { - updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction); - if (updateParentsModificationTimeRes.isRight()) { - log.debug("Failed to update modification time. ", oldGroupInstance.getName()); - actionResult = Either.right(updateParentsModificationTimeRes.right().value()); - } - } - } - if (actionResult == null) { - actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties()); - } - return actionResult; - } - - private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, - boolean inTranscation, boolean shouldCloseTransaction) { - - Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult; - Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult; - Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, - updatedGroupInstance.getModificationTime(), inTranscation); - if (updateComponentInstanceRes.isRight()) { - log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName()); - actionResult = Either.right(updateComponentInstanceRes.right().value()); - } else { - serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime()); - if (serviceMetadataUpdateResult.isRight()) { - log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value()))); - } else { - actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value())); - } - } - return actionResult; - } - - private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { - - Either<ImmutablePair<Component, User>, ResponseFormat> result = null; - Either<Component, ResponseFormat> validateComponentExistsRes = null; - User currUser = null; - Component component = null; - Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); - if (validationUserResult.isRight()) { - log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId); - result = Either.right(validationUserResult.right().value()); - } - if (result == null) { - currUser = validationUserResult.left().value(); - validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); - if (validateComponentExistsRes.isRight()) { - log.debug("Failed to validate service existing {}. ", serviceId); - result = Either.right(validateComponentExistsRes.right().value()); - } - } - if (result == null) { - component = validateComponentExistsRes.left().value(); - if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { - log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>(component, currUser)); - } - return result; - } - - private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { - - Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null; - GroupInstance groupInstance = null; - ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId); - if (foundComponentInstance == null) { - log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName())); - } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) { - groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); - if (groupInstance == null) { - log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName())); - } - } - if (actionResult == null) { - actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance)); - } - return actionResult; - } - - private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { - ComponentInstance componentInstance = null; - if (!CollectionUtils.isEmpty(component.getComponentInstances())) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); - } - return componentInstance; - } - - private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) { - Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false); - if (result.isLeft()) { - List<Role> roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.DESIGNER); - Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles); - if (validationRoleRes.isRight()) { - result = Either.right(validationRoleRes.right().value()); - } - } - return result; - } - - public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) { - - ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); - - if (serviceResultEither.isRight()) { - if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to found service with id {} ", serviceId); - Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); - } - - log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); - } - - Service service = serviceResultEither.left().value(); - UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); - return Either.left(dataTransfer); - } + private static final String STATUS_SUCCESS_200 = "200"; + + private static final String STATUS_DEPLOYED = "DEPLOYED"; + + @Autowired + private IElementOperation elementDao; + + @Autowired + private IDistributionEngine distributionEngine; + + @Autowired + private AuditCassandraDao auditCassandraDao; + + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @Autowired + private GroupBusinessLogic groupBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + private ServiceDistributionValidation serviceDistributionValidation; + + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class); + private static final String INITIAL_VERSION = "0.1"; + @Autowired + private ForwardingPathOperation forwardingPathOperation; + + @Autowired + private ForwardingPathValidator forwardingPathValidator; + + public ServiceBusinessLogic() { + log.debug("ServiceBusinessLogic started"); + } + + public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) { + + Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("check request state"); + Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user); + if (validateEnum.isRight()) { + return Either.right(validateEnum.right().value()); + } + DistributionTransitionEnum distributionTransition = validateEnum.left().value(); + AuditingActionEnum auditAction = distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT; + Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction); + if (commentResponse.isRight()) { + return Either.right(commentResponse.right().value()); + } + String comment = commentResponse.left().value(); + + Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment); + if (validateService.isRight()) { + return Either.right(validateService.right().value()); + } + Service service = validateService.left().value(); + Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment); + if (validateUser.isRight()) { + return Either.right(validateUser.right().value()); + } + user = validateUser.left().value(); + + // lock resource + + Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(responseFormat); + } + + try { + + DistributionStatusEnum newState; + if (distributionTransition == DistributionTransitionEnum.APPROVE) { + newState = DistributionStatusEnum.DISTRIBUTION_APPROVED; + } else { + newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; + } + Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState); + if (result.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); + log.debug("service {} is change destribuation status failed", service.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + Service updatedService = result.left().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, ComponentTypeEnum.SERVICE, ResourceAuditData.newBuilder().build(), comment); + return Either.left(result.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + + } + + public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<List<Map<String, Object>>, ActionStatus> result; + try { + + // Certified Version + if (componentVersion.endsWith(".0")) { + Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID); + if (eitherAuditingForCertified.isLeft()) { + result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value())); + } else { + result = Either.right(eitherAuditingForCertified.right().value()); + } + } + // Uncertified Version + else { + result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion); + } + } catch (Exception e) { + log.debug("get Audit Records failed with exception {}", e); + result = Either.right(ActionStatus.GENERAL_ERROR); + } + + if (result.isRight()) { + return Either.right(componentsUtils.getResponseFormat(result.right().value())); + } else { + return Either.left(result.left().value()); + } + + } + + private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) { + // First Query + Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); + + if (eitherprevVerAudit.isRight()) { + return Either.right(eitherprevVerAudit.right().value()); + } + + // Second Query + Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); + if (eitherCurrVerAudit.isRight()) { + return Either.right(eitherCurrVerAudit.right().value()); + } + + List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value()); + List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value()); + + List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>(); + duplicateElements.addAll(prevVerAuditList); + duplicateElements.retainAll(currVerAuditList); + + List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>(); + joinedNonDuplicatedList.addAll(prevVerAuditList); + joinedNonDuplicatedList.removeAll(duplicateElements); + joinedNonDuplicatedList.addAll(currVerAuditList); + + return Either.left(joinedNonDuplicatedList); + } + + private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) { + + List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>(); + for (AuditingGenericEvent auditEvent : prevVerAuditList) { + auditEvent.fillFields(); + prevVerAudit.add(auditEvent.getFields()); + } + return prevVerAudit; + } + + /** + * createService + * + * @param service + * - Service + * @param user + * - modifier data (userId) + * @return Either<Service, responseFormat> + */ + public Either<Service, ResponseFormat> createService(Service service, User user) { + + // get user details + Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + service.setCreatorUserId(user.getUserId()); + + // warn on overridden fields + checkFieldsForOverideAttampt(service); + // enrich object + log.debug("enrich service with version and state"); + service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setVersion(INITIAL_VERSION); + service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); + service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); + if (createServiceResponse.isRight()) { + return createServiceResponse; + } + return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); + } + + private void checkFieldsForOverideAttampt(Service service) { + checkComponentFieldsForOverrideAttempt(service); + if (service.getDistributionStatus() != null) { + log.info("Distribution Status cannot be defined by user. This field will be overridden by the application"); + } + } + + private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) { + log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult); + + try { + + createMandatoryArtifactsData(service, user); + createServiceApiArtifactsData(service, user); + setToscaArtifactsPlaceHolders(service, user); + Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service); + if (genericServiceEither.isRight()) + return Either.right(genericServiceEither.right().value()); + + generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); + + Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service); + + // service created successfully!!! + if (dataModelResponse.isLeft()) { + log.debug("Service created successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + ASDCKpiApi.countCreatedServicesKPI(); + return Either.left(dataModelResponse.left().value()); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE); + log.debug("audit before sending response"); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + + } finally { + graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service); + } + } + + @SuppressWarnings("unchecked") + private void createServiceApiArtifactsData(Service service, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + String serviceUniqueId = service.getUniqueId(); + Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts(); + if (artifactMap == null) + artifactMap = new HashMap<String, ArtifactDefinition>(); + + Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts(); + List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); + + List<CategoryDefinition> categories = service.getCategories(); + boolean isCreateArtifact = true; + if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { + for (String exlude : exludeServiceCategory) { + if (exlude.equalsIgnoreCase(categories.get(0).getName())) { + isCreateArtifact = false; + break; + } + } + + } + + if (serviceApiArtifacts != null && isCreateArtifact) { + Set<String> keys = serviceApiArtifacts.keySet(); + for (String serviceApiArtifactName : keys) { + Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName); + ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + + service.setServiceApiArtifacts(artifactMap); + } + } + + private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { + + Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum); + if (validationResponse.isRight()) { + return Either.right(validationResponse.right().value()); + } + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + service.setContactId(service.getContactId().toLowerCase()); + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + service.setInvariantUUID(invariantUUID); + + return Either.left(service); + } + + private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { + Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum); + if (componentsFieldsValidation.isRight()) { + return componentsFieldsValidation; + } + + log.debug("validate service name uniqueness"); + Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum); + if (serviceNameUniquenessValidation.isRight()) { + return serviceNameUniquenessValidation; + } + + log.debug("validate category"); + Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum); + if (categoryValidation.isRight()) { + return categoryValidation; + } + + // validate project name (ProjectCode) - mandatory in service + log.debug("validate projectName"); + Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum); + if (projectCodeValidation.isRight()) { + return projectCodeValidation; + } + + log.debug("validate service type"); + Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum); + if (serviceTypeValidation.isRight()) { + return serviceTypeValidation; + } + + log.debug("validate service role"); + Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum); + if (serviceRoleValidation.isRight()) { + return serviceRoleValidation; + } + + return Either.left(true); + + } + + private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) { + log.debug("validate Service category"); + + if (service.getCategories() == null || service.getCategories().size() == 0) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + + Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories()); + if (validatCategory.isRight()) { + ResponseFormat responseFormat = validatCategory.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + return Either.left(true); + } + + public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); + + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map<String, Boolean> result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } + + public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { + this.auditCassandraDao = auditingDao; + } + + public ArtifactsBusinessLogic getArtifactBl() { + return artifactsBusinessLogic; + } + + public void setArtifactBl(ArtifactsBusinessLogic artifactBl) { + this.artifactsBusinessLogic = artifactBl; + } + + public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) { + Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + + Service currentService = storageStatus.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate); + if (validationRsponse.isRight()) { + log.info("service update metadata: validations field."); + return validationRsponse; + } + Service serviceToUpdate = validationRsponse.left().value(); + // lock resource + + Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); + if (updateResponse.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); + log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + return Either.left(updateResponse.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) { + Service serviceToDelete = initServiceToDeletePaths(serviceId, pathIdsToDelete); + Either<User, ResponseFormat> eitherCreator = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + Service service = storageStatus.left().value(); + Either<Set<String>, StorageOperationStatus> result = null; + if (lock) { + Either<Boolean, ResponseFormat> lockResult = lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); + if (lockResult.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + } + try{ + result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete); + if (result.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", service.getName(), result.right().value()); + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); + } + titanDao.commit(); + log.debug("The service with system name {} locked. ", service.getSystemName()); + + } catch (Exception e){ + log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); + } + return Either.left(result.left().value()); + } + + private Service initServiceToDeletePaths(String serviceId, Collection<String> pathIdsToDelete) { + Service serviceToDelete = new Service(); + serviceToDelete.setUniqueId(serviceId); + serviceToDelete.setForwardingPaths(new HashMap<>()); + pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition())); + return serviceToDelete; + } + + public Either<Service, ResponseFormat> updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock); + } + + public Either<Service, ResponseFormat> createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock); + } + + private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path){ + ForwardingPathDataDefinition dataDefinition = new ForwardingPathDataDefinition(path.getName()); + dataDefinition.setName(Strings.nullToEmpty(path.getName()).trim()); + dataDefinition.setProtocol(Strings.nullToEmpty(path.getProtocol()).trim()); + dataDefinition.setDestinationPortNumber(Strings.nullToEmpty(path.getDestinationPortNumber()).trim()); + dataDefinition.setUniqueId(path.getUniqueId()); + dataDefinition.setPathElements(path.getPathElements()); + dataDefinition.setDescription(path.getDescription()); + dataDefinition.setToscaResourceName(path.getToscaResourceName()); + return dataDefinition; + } + + private Either<Service, ResponseFormat> createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) { + Either<Service, ResponseFormat> eitherCreator1 = validateUserAndRole(serviceUpdate, user, errorContext); + if (eitherCreator1 != null) return eitherCreator1; + + Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths(); + + Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths = + forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue())))); + + Either<Boolean, ResponseFormat> booleanResponseFormatEither = forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), + serviceId, isUpdate); + if(booleanResponseFormatEither.isRight()){ + return Either.right(booleanResponseFormatEither.right().value()); + } + + Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); + + if(serviceStorageOperationStatusEither.isRight()){ + StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); + log.debug("Failed to fetch service information by service id, error {}", errorStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + } + Service storedService = serviceStorageOperationStatusEither.left().value(); + + Set<ForwardingPathDataDefinition> forwardingPathDataDefinitions = trimmedForwardingPaths.entrySet().stream().map(entry -> entry.getValue()) + .collect(Collectors.toSet()); + + Either<ForwardingPathDataDefinition, StorageOperationStatus> result; + Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME); + if (forwardingPathOrigin.isRight()) { + StorageOperationStatus errorStatus = forwardingPathOrigin.right().value(); + log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + } + Component component = forwardingPathOrigin.left().value(); + final String toscaResourceName; + if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) { + toscaResourceName = ((Resource) component).getToscaResourceName(); + } else { + toscaResourceName = ""; + } + Either<Boolean, ResponseFormat> lockResult = null; + if (lock) { + lockResult = + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); + if (lockResult.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(), + lockResult.right().value().getFormattedMessage()); + return Either.right(lockResult.right().value()); + } else { + log.debug("The service with system name {} locked. ", storedService.getSystemName()); + } + } + Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>(); + try { + trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName)); + + try { + for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) { + if (isUpdate) { + result = forwardingPathOperation.updateForwardingPath(serviceId, forwardingPathDataDefinition); + } else { + result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition); + } + if (result.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), + "")); + } else { + ForwardingPathDataDefinition fpDataDefinition = result.left().value(); + resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition); + } + } + + } catch (Exception e) { + titanDao.rollback(); + log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), + e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + } finally { + if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); + } + } + Service service = createServiceWithForwardingPathForResponse(serviceId, resultMap); + return Either.left(service); + } + + private Service createServiceWithForwardingPathForResponse(String serviceId, Map<String,ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) { + Service service = new Service(); + service.setUniqueId(serviceId); + service.setForwardingPaths(forwardingPathDataDefinitionMap); + return service; + } + + private Either<Service, ResponseFormat> validateUserAndRole(Service serviceUpdate, User user, String errorContext) { + Either<User, ResponseFormat> eitherCreator = validateUser(user, errorContext, serviceUpdate, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + return null; + }private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion()); + Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String creatorUserIdUpdated = serviceUpdate.getCreatorUserId(); + String creatorUserIdCurrent = currentService.getCreatorUserId(); + if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) { + log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated); + } + + String creatorFullNameUpdated = serviceUpdate.getCreatorFullName(); + String creatorFullNameCurrent = currentService.getCreatorFullName(); + if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) { + log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated); + } + + String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId(); + String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId(); + if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) { + log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated); + } + + String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName(); + String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName(); + if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) { + log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated); + } + + response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus(); + DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus(); + if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals(distributionStatusCurrent != null ? distributionStatusCurrent.name() : null)) { + log.info("update service: received request to update distributionStatus to {}. the field is read only, ignoring.", distributionStatusUpdated); + } + + if (serviceUpdate.getProjectCode() != null) { + response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + } + + response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + Long creationDateUpdated = serviceUpdate.getCreationDate(); + Long creationDateCurrent = currentService.getCreationDate(); + if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) { + log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated); + } + + String versionUpdated = serviceUpdate.getVersion(); + String versionCurrent = currentService.getVersion(); + if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { + log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); + } + + response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateContactId(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate(); + Long lastUpdateDateCurrent = currentService.getLastUpdateDate(); + if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) { + log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated); + } + + LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState(); + LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState(); + if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) { + log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated); + } + + Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion(); + Boolean isHighestVersionCurrent = currentService.isHighestVersion(); + if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) { + log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated); + } + + String uuidUpdated = serviceUpdate.getUUID(); + String uuidCurrent = currentService.getUUID(); + if (!uuidCurrent.equals(uuidUpdated)) { + log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); + } + + response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String currentInvariantUuid = currentService.getInvariantUUID(); + String updatedInvariantUuid = serviceUpdate.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Product invariant UUID is automatically set and cannot be updated"); + serviceUpdate.setInvariantUUID(currentInvariantUuid); + } + validateAndUpdateEcompNaming(currentService, serviceUpdate); + + currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); + + return Either.left(currentService); + + } + + private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) { + Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming(); + Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming(); + if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr.equals(isEcompoGeneratedUpdate)) { + currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate); + } + String namingPolicyUpd = serviceUpdate.getNamingPolicy(); + if (!currentService.isEcompGeneratedNaming()) { + if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) { + log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false"); + currentService.setNamingPolicy(""); + } else { + currentService.setNamingPolicy(namingPolicyUpd); + } + }else{ + currentService.setNamingPolicy(namingPolicyUpd); + } + } + + private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + String contactIdUpdated = serviceUpdate.getContactId(); + String contactIdCurrent = currentService.getContactId(); + if (!contactIdCurrent.equals(contactIdUpdated)) { + Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction); + if (validatContactId.isRight()) { + ResponseFormat errorRespons = validatContactId.right().value(); + return Either.right(errorRespons); + } + currentService.setContactId(contactIdUpdated.toLowerCase()); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + List<String> tagsUpdated = serviceUpdate.getTags(); + List<String> tagsCurrent = currentService.getTags(); + if (tagsUpdated == null || tagsUpdated.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS); + componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { + Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setTags(tagsUpdated); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + String descriptionUpdated = serviceUpdate.getDescription(); + String descriptionCurrent = currentService.getDescription(); + if (!descriptionCurrent.equals(descriptionUpdated)) { + Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction); + if (validateDescriptionResponse.isRight()) { + ResponseFormat errorRespons = validateDescriptionResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setDescription(serviceUpdate.getDescription()); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + String projectCodeUpdated = serviceUpdate.getProjectCode(); + String projectCodeCurrent = currentService.getProjectCode(); + if (!projectCodeCurrent.equals(projectCodeUpdated)) { + + Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); + if (validatProjectCodeResponse.isRight()) { + ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setProjectCode(projectCodeUpdated); + + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + String iconUpdated = serviceUpdate.getIcon(); + String iconCurrent = currentService.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction); + if (validatIconResponse.isRight()) { + ResponseFormat errorRespons = validatIconResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setIcon(iconUpdated); + } else { + log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) { + String serviceNameUpdated = serviceUpdate.getName(); + String serviceNameCurrent = currentService.getName(); + if (!serviceNameCurrent.equals(serviceNameUpdated)) { + if (!hasBeenCertified) { + Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction); + if (validatServiceNameResponse.isRight()) { + ResponseFormat errorRespons = validatServiceNameResponse.right().value(); + return Either.right(errorRespons); + } + + Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction); + if (serviceNameUniquenessValidation.isRight()) { + return serviceNameUniquenessValidation; + } + currentService.setName(serviceNameUpdated); + currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); + currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated)); + + } else { + log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { + String updatedServiceType = updatedService.getServiceType(); + String currentServiceType = currentService.getServiceType(); + if (!currentServiceType.equals(updatedServiceType)) { + Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction); + if (validateServiceType.isRight()) { + ResponseFormat errorResponse = validateServiceType.right().value(); + componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + currentService.setServiceType(updatedServiceType); + } + return Either.left(true); + } + + protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + String serviceType = ((Service)component).getServiceType(); + if (serviceType != null){ + serviceType = cleanUpText(serviceType); + Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType); + if (validateServiceType.isRight()) { + ResponseFormat responseFormat = validateServiceType.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + return Either.left(true); + } else { + return Either.left(false); + } + } + + + private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) { + if (serviceType.equals("")){ + return Either.left(true); + } else { + if (!ValidationUtils.validateServiceTypeLength(serviceType)) { + log.info("service type exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateIsEnglish(serviceType)) { + log.info("service type is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { + String updatedServiceRole = updatedService.getServiceRole(); + String currentServiceRole = currentService.getServiceRole(); + if (!currentServiceRole.equals(updatedServiceRole)) { + Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction); + if (validateServiceRole.isRight()) { + ResponseFormat errorResponse = validateServiceRole.right().value(); + componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + currentService.setServiceRole(updatedServiceRole); + } + return Either.left(true); + } + + protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + String serviceRole = ((Service)component).getServiceRole(); + if (serviceRole != null){ + serviceRole = cleanUpText(serviceRole); + + Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole); + if (validateServiceRole.isRight()) { + ResponseFormat responseFormat = validateServiceRole.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + return Either.left(true); + } else { + return Either.left(false); + } + } + + + private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) { + if (serviceRole.equals("")){ + return Either.left(true); + } else { + if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { + log.info("service role exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateIsEnglish(serviceRole)) { + log.info("service role is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + + + private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories(); + List<CategoryDefinition> categoryCurrent = currentService.getCategories(); + Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction); + if (validatCategoryResponse.isRight()) { + ResponseFormat errorRespons = validatCategoryResponse.right().value(); + return Either.right(errorRespons); + } + if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { + if (!hasBeenCertified) { + currentService.setCategories(categoryUpdated); + } else { + log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + + } + + public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) { + if (list != null) { + if (list.size() > 1) { + log.debug("Must be only one category for service"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); + return Either.right(responseFormat); + } + CategoryDefinition category = list.get(0); + if (category.getSubcategories() != null) { + log.debug("Subcategories cannot be defined for service"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY); + return Either.right(responseFormat); + } + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + return Either.right(responseFormat); + } + + log.debug("validating service category {} against valid categories list", list); + Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories(); + if (categorys.isRight()) { + log.debug("failed to retrive service categories from Titan"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); + return Either.right(responseFormat); + } + List<CategoryDefinition> categoryList = categorys.left().value(); + for (CategoryDefinition value : categoryList) { + if (value.getName().equals(category.getName())) { + return Either.left(true); + } + } + log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); + } + return Either.left(false); + } + + public Either<ServiceRelations, ResponseFormat> getServiceComponentsRelations(String serviceId, User user) { + Either<Service, ResponseFormat> serviceResponseFormatEither = getService(serviceId, user); + if (serviceResponseFormatEither.isRight()){ + return Either.right(serviceResponseFormatEither.right().value()); + } + final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value()); + return Either.left(serviceRelations); + + + }public ResponseFormat deleteService(String serviceId, User user) { + ResponseFormat responseFormat; + String ecompErrorContext = "delete service"; + + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + user = eitherCreator.left().value(); + + Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId); + if (serviceStatus.isRight()) { + log.debug("failed to get service {}", serviceId); + return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), ""); + } + + Service service = serviceStatus.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + + result = markComponentToDelete(service); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) { + ResponseFormat responseFormat; + String ecompErrorContext = "delete service"; + Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return validateEmptyResult.right().value(); + } + + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + user = eitherCreator.left().value(); + + Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); + if (getResult.isRight()) { + return getResult.right().value(); + } + Service service = getResult.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + result = markComponentToDelete(service); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); + } + } + + public Either<Service, ResponseFormat> getService(String serviceId, User user) { + String ecompErrorContext = "Get service"; + Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + log.debug("failed to get service by id {}", serviceId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId)); + } + + if(!(storageStatus.left().value() instanceof Service)){ + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId)); + } + Service service = storageStatus.left().value(); + return Either.left(service); + + + + + } + + public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) { + Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); + if (storageStatus.isRight()) { + log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName)); + } + Service service = storageStatus.left().value(); + return Either.left(service); + } + + @SuppressWarnings("unchecked") + private void createMandatoryArtifactsData(Service service, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + String serviceUniqueId = service.getUniqueId(); + Map<String, ArtifactDefinition> artifactMap = service.getArtifacts(); + if (artifactMap == null) + artifactMap = new HashMap<String, ArtifactDefinition>(); + + Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts(); + List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); + + String category = service.getCategories().get(0).getName(); + boolean isCreateArtifact = true; + if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { + for (String exlude : exludeServiceCategory) { + if (exlude.equalsIgnoreCase(category)) { + isCreateArtifact = false; + break; + } + } + + } + + if (informationalServiceArtifacts != null && isCreateArtifact) { + Set<String> keys = informationalServiceArtifacts.keySet(); + for (String informationalServiceArtifactName : keys) { + Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName); + ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + } + + service.setArtifacts(artifactMap); + } + } + + private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) { + + ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); + + if (isServiceApi) { + artifactInfo.setMandatory(false); + artifactInfo.setServiceApi(true); + } + return artifactInfo; + } + + private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) { + DistributionTransitionEnum transitionEnum = null; + + transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); + if (transitionEnum == null) { + BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution"); + log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(error); + } + + return Either.left(transitionEnum); + } + + private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) { + String data = comment.getUserRemarks(); + + if (data == null || data.trim().isEmpty()) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); + log.debug("user comment cannot be empty or null."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + data = ValidationUtils.removeNoneUtf8Chars(data); + data = ValidationUtils.removeHtmlTags(data); + data = ValidationUtils.normaliseWhitespace(data); + data = ValidationUtils.stripOctets(data); + + if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); + log.debug("user comment exceeds limit."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); + } + if (!ValidationUtils.validateIsEnglish(data)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(data); + } + + private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, auditAction, serviceId, ComponentTypeEnum.SERVICE, comment); + return Either.right(responseFormat); + } + Service service = storageStatus.left().value(); + + if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { + log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(responseFormat); + } + return Either.left(service); + } + + private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { + log.debug("get user from DB"); + + // get user details + Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + List<Role> roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.GOVERNOR); + roles.add(Role.OPS); + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + return Either.left(user); + } + + private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) { + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, component, auditAction, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(component.getVersion()).build(), comment); + } + + private String getEnvNameFromConfiguration() { + String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + log.trace("Update environment name to be {}", configuredEnvName); + return configuredEnvName; + } + + public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) { + + Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data); + if (activationRequestInformationEither.isRight()) { + return Either.right(activationRequestInformationEither.right().value()); + } + + ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value(); + + Either<String, ResponseFormat> result = null; + ResponseFormat response = null; + String did = ThreadLocalsHolder.getUuid(); + Service service = activationRequestInformation.getServiceToActivate(); + + StorageOperationStatus readyForDistribution = distributionEngine.verifyServiceHasDeploymentArtifacts(service); + if (readyForDistribution.equals(StorageOperationStatus.OK)) { + result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier); + } else { + response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envId); + result = Either.right(response); + } + return result; + } + + public Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) { + String envName = getEnvNameFromConfiguration(); + INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext); + ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier.getUserId(), modifier.getFullName()); + if (notifyServiceResponse == ActionStatus.OK) { + return Either.left(did); + } else { + BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); + log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESPONSE_FROM_PROXY); + return Either.right(error); + } + } + + public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { + + Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + User user = eitherCreator.left().value(); + + Either<Service, ResponseFormat> result = null; + ResponseFormat response = null; + Service updatedService = null; + String did = ThreadLocalsHolder.getUuid(); + // DE194021 + String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + if (configuredEnvName != null && false == envName.equals(configuredEnvName)) { + log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName); + envName = configuredEnvName; + } + // DE194021 + + ServletContext servletContext = request.getSession().getServletContext(); + boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE + if (!isDistributionEngineUp) { + BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN"); + log.debug("Distribution Engine is DOWN"); + response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(response); + } + + Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId); + if (serviceRes.isRight()) { + log.debug("failed retrieving service"); + response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); + componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().build(), did); + return Either.right(response); + } + Service service = serviceRes.left().value(); + String dcurrStatus = service.getDistributionStatus().name(); + String updatedStatus = dcurrStatus; + StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(service, envName); + if (readyForDistribution.equals(StorageOperationStatus.OK)) { + INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null); + ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName()); + if (notifyServiceResponse == ActionStatus.OK) { + Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED); + if (updateStateRes.isLeft() && updateStateRes.left().value() != null) { + updatedService = updateStateRes.left().value(); + updatedStatus = updatedService.getDistributionStatus().name(); + } else { + // The response is not relevant + updatedService = service; + } + ASDCKpiApi.countActivatedDistribution(); + response = componentsUtils.getResponseFormat(ActionStatus.OK); + result = Either.left(updatedService); + } else { + BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); + log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); + response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(response); + } + } else { + response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envName); + result = Either.right(response); + } + componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().distributionStatus(dcurrStatus).build(), + ResourceAuditData.newBuilder().distributionStatus(updatedStatus).build(), service.getName(), + null, null, did); + return result; + } + + // convert to private after deletion of temp url + public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { + + Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + String serviceId = service.getUniqueId(); + Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state); + if (result.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); + log.debug("service {} change distribution status failed", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + return Either.left(result.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) { + + Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("mark distribution deployed"); + + AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; + Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId); + if (getServiceResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId); + log.debug("service {} not found", serviceId); + ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); + + return Either.right(responseFormat); + } + + Service service = getServiceResponse.left().value(); + + Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service); + if (validateRoleForDeploy.isRight()) { + return Either.right(validateRoleForDeploy.right().value()); + } + user = validateRoleForDeploy.left().value(); + + return checkDistributionAndDeploy(did, user, auditAction, service); + + } + + public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) { + Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri -> + // Only one VF Module Artifact per instance - add it to a list of one + buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri); + + return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator); + + } + + private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) { + List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>(); + + if (ri.getOriginType() == OriginTypeEnum.VF) { + asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock, inTransaction)); + } + return asList; + } + + private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) { + Map<String, ArtifactDefinition> deploymentArtifacts = currVF.getDeploymentArtifacts(); + if(currVF.getGroupInstances() != null){ + currVF.getGroupInstances().stream().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts)); + } + return currVF.getGroupInstances(); + } + + private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) { + ArtifactDefinition vfModuleAertifact = null; + if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { + Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); + if (optionalVfModuleArtifact.isPresent()) { + vfModuleAertifact = optionalVfModuleArtifact.get(); + } + } + if (vfModuleAertifact == null) { + Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement()); + if (createVfModuleArtifact.isLeft()) { + vfModuleAertifact = createVfModuleArtifact.left().value(); + } else { + responseWrapper.setInnerElement(createVfModuleArtifact.right().value()); + } + } + return vfModuleAertifact; + } + + private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper) { + // Converts GroupDefinition to VfModuleArtifactPayload which is the + // format used in the payload + + List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>(); + if (groupsForCurrVF != null) { + for (GroupInstance groupInstance : groupsForCurrVF) { + VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance); + vfModulePayloadForCurrVF.add(modulePayload); + } + Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); + + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); + payloadWrapper.setInnerElement(vfModulePayloadString); + } + + } + + private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition vfModuleAertifact = null; + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + Wrapper<String> payloadWrapper = new Wrapper<>(); + List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); + if (responseWrapper.isEmpty()) { + fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper); + } + if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { + vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); + } + if (responseWrapper.isEmpty() && vfModuleAertifact != null) { + vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service); + } + + Either<ArtifactDefinition, ResponseFormat> result; + if (responseWrapper.isEmpty()) { + result = Either.left(vfModuleAertifact); + } else { + result = Either.right(responseWrapper.getInnerElement()); + } + + return result; + } + + private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) { + ArtifactDefinition result = null; + Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, () -> System.currentTimeMillis(), + () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); + if (eitherPayload.isLeft()) { + result = eitherPayload.left().value(); + } else { + responseWrapper.setInnerElement(eitherPayload.right().value()); + } + if (result == null) { + result = vfModuleArtifact; + } + + return result; + } + + private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) { + + ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition(); + String newCheckSum = null; + + vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact"); + vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata"); + vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType()); + vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata"); + vfModuleArtifactDefinition.setTimeout(0); + vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json"); + vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString); + if (vfModulePayloadString != null) { + newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes()); + } + vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); + + Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); + + Either<ArtifactDefinition, ResponseFormat> result; + if (addArifactToComponent.isLeft()) { + result = Either.left(addArifactToComponent.left().value()); + } else { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value()))); + } + + return result; + } + + public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) { + + Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance -> + // Get All Deployment Artifacts + service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()). + // Filter in Only Heat Env + filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())). + // Create ArtifactGenerator from those Artifacts + map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction, resourceInstance.getUniqueId())).collect(Collectors.toList()); + + return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator); + + } + + private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) { + + // Get Flat List of (Callable) ArtifactGenerator for all the RI in the + // service + if (service.getComponentInstances() != null) { + List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); + if (artifactGenList != null && !artifactGenList.isEmpty()) { + for (ArtifactGenerator<CallVal> entry : artifactGenList) { + Either<CallVal, ResponseFormat> callRes; + try { + callRes = entry.call(); + if (callRes.isRight()) { + log.debug("Failed to generate artifact error : {}", callRes.right().value()); + return Either.right(callRes.right().value()); + } + } catch (Exception e) { + log.debug("Failed to generate artifact exception : {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } + } + Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + + Service currentService = storageStatus.left().value(); + + return Either.left(currentService); + + } + + abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> { + + } + + class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> { + ArtifactDefinition artifactDefinition; + Service service; + String resourceInstanceName; + User modifier; + String instanceId; + boolean shouldLock; + boolean inTransaction; + + HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) { + this.artifactDefinition = artifactDefinition; + this.service = service; + this.resourceInstanceName = resourceInstanceName; + this.modifier = modifier; + this.shouldLock = shouldLock; + this.instanceId = instanceId; + this.inTransaction = inTransaction; + } + + @Override + public Either<ArtifactDefinition, ResponseFormat> call() throws Exception { + return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId); + } + + public ArtifactDefinition getArtifactDefinition() { + return artifactDefinition; + } + + } + + class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> { + private User user; + private ComponentInstance componentInstance; + private Service service; + boolean shouldLock; + boolean inTransaction; + + @Override + public Either<ArtifactDefinition, ResponseFormat> call() throws Exception { + return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction); + } + + private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock, boolean inTransaction) { + super(); + this.user = user; + this.componentInstance = componentInstance; + this.service = service; + this.shouldLock = shouldLock; + this.inTransaction = inTransaction; + } + + } + + private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { + boolean isDeployed = isDistributionDeployed(did, service); + if (isDeployed) { + return Either.left(service); + } + Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service); + if (distributionSuccess.isRight()) { + return Either.right(distributionSuccess.right().value()); + } + + log.debug("mark distribution {} as deployed - success", did); + componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user); + return Either.left(service); + } + + private boolean isDistributionDeployed(String did, Service service) { + Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); + + boolean isDeployed = false; + if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) { + // already deployed + log.debug("distribution {} is already deployed", did); + isDeployed = true; + } + return isDeployed; + } + + protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) { + + log.trace("checkDistributionSuccess"); + // get all "DRequest" records for this distribution + + Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + if (distRequestsResponse.isRight()) { + ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value()); + return Either.right(error); + } + + List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value(); + if (distributionRequests.isEmpty()) { + BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did); + log.info("distribution {} is not found", did); + ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND); + return Either.right(error); + } + boolean isRequestSucceeded = false; + for (ResourceAdminEvent event : distributionRequests) { + String eventStatus = event.getStatus(); + if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { + isRequestSucceeded = true; + break; + } + } + + // get all "DNotify" records for this distribution + Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + if (distNotificationsResponse.isRight()) { + ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value()); + return Either.right(error); + } + + List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value(); + boolean isNotificationsSucceeded = false; + for (DistributionNotificationEvent event : distributionNotifications) { + String eventStatus = event.getStatus(); + if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { + isNotificationsSucceeded = true; + break; + } + } + + // if request failed OR there are notifications that failed + if (!(isRequestSucceeded && isNotificationsSucceeded)) { + + log.info("distribution {} has failed", did); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); + auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); + return Either.right(error); + } + return Either.left(true); + } + + private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) { + + ResponseFormat error = componentsUtils.getResponseFormat(status, params); + String message = ""; + if (error.getMessageId() != null) { + message = error.getMessageId() + ": "; + } + message += error.getFormattedMessage(); + + if (service != null) { + componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user); + } else { + componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user); + } + return error; + } + + private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { + Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); + log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); + auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); + return Either.right(responseFormat); + } + user = eitherCreator.left().value(); + log.debug("validate user role"); + List<Role> roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.OPS); + Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null); + if (validateRes.isRight()) { + log.info("role {} is not allowed to perform this action", user.getRole()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + return Either.left(user); + + } + + @Override + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + + } + + @Override + public Either<List<String>, ResponseFormat> deleteMarkedComponents() { + return deleteMarkedComponents(ComponentTypeEnum.SERVICE); + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + @Override + public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + + Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + if (getComponentRes.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); + return Either.right(responseFormat); + } + + List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances(); + + return Either.left(componentInstances); + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation) { + this.forwardingPathOperation = forwardingPathOperation; + } + + @Override + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + }/** + * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date + * + * @param modifier + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param newProperties + * @return + */ + public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) { + + Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null; + Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes; + Component component = null; + Either<Boolean, ResponseFormat> lockResult = null; + log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId); + try { + validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier); + if (validateUserAndComponentRes.isRight()) { + log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId); + actionResult = Either.right(validateUserAndComponentRes.right().value()); + } + if (actionResult == null) { + component = validateUserAndComponentRes.left().value().getKey(); + lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service"); + if (lockResult.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage()); + actionResult = Either.right(lockResult.right().value()); + } else { + log.debug("The service with system name {} locked. ", component.getSystemName()); + } + } + if (actionResult == null) { + actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); + if (actionResult.isRight()) { + log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage()); + } + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service); + } + } + return actionResult; + } + + private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) { + + Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null; + Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes; + Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes; + ComponentInstance relatedComponentInstance = null; + GroupInstance oldGroupInstance = null; + Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null; + GroupInstance updatedGroupInstance = null; + boolean inTransaction = true; + boolean shouldCloseTransaction = true; + findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId); + if (findGroupInstanceRes.isRight()) { + log.debug("Group instance {} not found. ", groupInstanceId); + actionResult = Either.right(findGroupInstanceRes.right().value()); + } + if (actionResult == null) { + oldGroupInstance = findGroupInstanceRes.left().value().getValue(); + relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); + updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction); + if (updateGroupInstanceResult.isRight()) { + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(updateGroupInstanceResult.right().value()); + } + } + if (actionResult == null) { + updatedGroupInstance = updateGroupInstanceResult.left().value(); + if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) { + updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction); + if (updateParentsModificationTimeRes.isRight()) { + log.debug("Failed to update modification time. ", oldGroupInstance.getName()); + actionResult = Either.right(updateParentsModificationTimeRes.right().value()); + } + } + } + if (actionResult == null) { + actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties()); + } + return actionResult; + } + + private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, + boolean inTranscation, boolean shouldCloseTransaction) { + + Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult; + Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult; + Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, + updatedGroupInstance.getModificationTime(), inTranscation); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(updateComponentInstanceRes.right().value()); + } else { + serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime()); + if (serviceMetadataUpdateResult.isRight()) { + log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value()))); + } else { + actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value())); + } + } + return actionResult; + } + + private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { + + Either<ImmutablePair<Component, User>, ResponseFormat> result = null; + Either<Component, ResponseFormat> validateComponentExistsRes = null; + User currUser = null; + Component component = null; + Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); + if (validationUserResult.isRight()) { + log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId); + result = Either.right(validationUserResult.right().value()); + } + if (result == null) { + currUser = validationUserResult.left().value(); + validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); + if (validateComponentExistsRes.isRight()) { + log.debug("Failed to validate service existing {}. ", serviceId); + result = Either.right(validateComponentExistsRes.right().value()); + } + } + if (result == null) { + component = validateComponentExistsRes.left().value(); + if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>(component, currUser)); + } + return result; + } + + private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { + + Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null; + GroupInstance groupInstance = null; + ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId); + if (foundComponentInstance == null) { + log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName())); + } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) { + groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); + if (groupInstance == null) { + log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName())); + } + } + if (actionResult == null) { + actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance)); + } + return actionResult; + } + + private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { + ComponentInstance componentInstance = null; + if (!CollectionUtils.isEmpty(component.getComponentInstances())) { + componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); + } + return componentInstance; + } + + private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) { + Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false); + if (result.isLeft()) { + List<Role> roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.DESIGNER); + Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles); + if (validationRoleRes.isRight()) { + result = Either.right(validationRoleRes.right().value()); + } + } + return result; + } + + public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); + + if (serviceResultEither.isRight()) { + if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found service with id {} ", serviceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); + } + + log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); + } + + Service service = serviceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); + return Either.left(dataTransfer); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java deleted file mode 100644 index d1cc93acc8..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.springframework.stereotype.Component; - -@Component("serviceComponentInstanceBusinessLogic") -public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - return NodeTypeEnum.Resource; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java deleted file mode 100644 index c5db7ee022..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component("vfComponentInstanceBusinessLogic") -public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - private static Logger log = LoggerFactory.getLogger(VFComponentInstanceBusinessLogic.class.getName()); - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - return NodeTypeEnum.Resource; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java new file mode 100644 index 0000000000..6347bc2eaf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java @@ -0,0 +1,44 @@ +package org.openecomp.sdc.be.components.impl.exceptions; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +public class ComponentException extends RuntimeException { + + /** + * This class will be initialized either by action status and params or by ResponseFormat + */ + + private final transient ResponseFormat responseFormat; + + private final ActionStatus actionStatus; + private final String[] params; + + public ComponentException(ResponseFormat responseFormat) { + this(responseFormat, ActionStatus.OK, null); + } + + public ComponentException(ActionStatus actionStatus, String... params) { + this(null, actionStatus, params); + } + + private ComponentException(ResponseFormat responseFormat, ActionStatus actionStatus, String... params) { + this.actionStatus = actionStatus; + this.params = params; + this.responseFormat = responseFormat; + } + + public ResponseFormat getResponseFormat() { + return responseFormat; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } + + public String[] getParams() { + return params; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java index 7f6abe7f2c..236be437af 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java @@ -1,9 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -20,7 +17,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; @org.springframework.stereotype.Component public class GenericTypeBusinessLogic { @@ -81,6 +80,9 @@ public class GenericTypeBusinessLogic { } private <T extends Component> String getGenericTypeToscaName(T component) { + if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){ + return component.getDerivedFromGenericType(); + } return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java new file mode 100644 index 0000000000..30a93fa0bc --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class PolicyTypeImportUtils { + + private PolicyTypeImportUtils() { + } + + public static boolean isPolicyTypesEquals(PolicyTypeDefinition pt1, PolicyTypeDefinition pt2) { + if (pt1 == pt2) { + return true; + } + if (pt1 == null || pt2 == null) { + return false; + } + return Objects.equals(pt1.getType(), pt2.getType()) && + Objects.equals(pt1.getVersion(), pt2.getVersion()) && + Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) && + Objects.equals(pt1.getTargets(), pt2.getTargets()) && + Objects.equals(pt1.getMetadata(), pt2.getMetadata()) && + Objects.equals(pt1.getDescription(), pt2.getDescription()) && + PolicyTypeImportUtils.isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties()); + } + + private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) { + if (pt1Props == pt2Props) { + return true; + } + if (pt1Props == null || pt2Props == null) { + return false; + } + if (isPropertiesListSizesNotEquals(pt1Props, pt2Props)) { + return false; + } + Map<String, PropertyDefinition> pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName); + long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count(); + return numberOfEqualsProperties == pt1Props.size(); + } + + private static boolean policyPropertyEquals(PropertyDefinition pt1Prop, PropertyDefinition pt2Prop) { + if (pt1Prop == pt2Prop) { + return true; + } + if (pt1Prop == null || pt2Prop == null) { + return false; + } + return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) && + Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition()) && + Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) && + Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword()) && + Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) && + Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType()) && + Objects.equals(pt1Prop.getType(), pt2Prop.getType()); + } + + private static boolean isPropertiesListSizesNotEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) { + return CollectionUtils.isEmpty(pt1Props) && CollectionUtils.isNotEmpty(pt2Props) || + CollectionUtils.isEmpty(pt2Props) && CollectionUtils.isNotEmpty(pt1Props) || + pt1Props.size() != pt2Props.size(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java new file mode 100644 index 0000000000..df98a7f707 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java @@ -0,0 +1,66 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; +@org.springframework.stereotype.Component +public class GroupMembersUpdateOperation implements PostChangeVersionOperation { + + private static final Logger log = LoggerFactory.getLogger(GroupMembersUpdateOperation.class); + private final GroupsOperation groupsOperation; + private final ComponentsUtils componentsUtils; + + public GroupMembersUpdateOperation(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) { + this.groupsOperation = groupsOperation; + this.componentsUtils = componentsUtils; + } + + @Override + public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + return updateGroupMembersOnChangeVersion(container, prevVersion, newVersion); + } + + private ActionStatus updateGroupMembersOnChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#updateGroupMembersOnChangeVersion - replacing all group members for component instance {} with new component instance.", prevVersion.getUniqueId(), newVersion.getUniqueId()); + if (isEmpty(container.getGroups())) { + log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups.", container.getUniqueId()); + return ActionStatus.OK; + } + List<GroupDefinition> groupsWithPrevInstAsMember = container.resolveGroupsByMember(prevVersion.getUniqueId()); + if (isEmpty(groupsWithPrevInstAsMember)) { + log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups with component instance {} as member.", container.getUniqueId(), prevVersion.getUniqueId()); + return ActionStatus.OK; + } + replacePrevInstanceMemberWithNewInstance(prevVersion, newVersion, groupsWithPrevInstAsMember); + return updateGroups(container, groupsWithPrevInstAsMember); + } + + private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) { + log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId()); + return groupsOperation.updateGroups(container, groupsToUpdate) + .either(groupsUpdated -> ActionStatus.OK, + err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType())); + } + + private void replacePrevInstanceMemberWithNewInstance(ComponentInstance prevVersion, ComponentInstance newVersion, List<GroupDefinition> groupsWithPrevInstAsMember) { + groupsWithPrevInstAsMember.forEach(grp -> replacePrevInstanceMemberWithNewInstance(grp, prevVersion.getUniqueId(), newVersion.getUniqueId())); + } + + private void replacePrevInstanceMemberWithNewInstance(GroupDefinition groupDefinition, String prevInstanceId, String newInstanceId) { + Map<String, String> membersNameToId = groupDefinition.getMembers(); + String prevInstanceMemberName = MapUtils.invertMap(membersNameToId).get(prevInstanceId).toString(); + membersNameToId.replace(prevInstanceMemberName, newInstanceId); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java new file mode 100644 index 0000000000..8824b2e097 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.function.UnaryOperator; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +@org.springframework.stereotype.Component +public class PolicyTargetsUpdateOperation implements PostChangeVersionOperation { + + private static final Logger log = LoggerFactory.getLogger(PolicyTargetsUpdateOperation.class); + private final ToscaOperationFacade toscaOperationFacade; + private final ComponentsUtils componentsUtils; + + public PolicyTargetsUpdateOperation(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + this.toscaOperationFacade = toscaOperationFacade; + this.componentsUtils = componentsUtils; + } + + @Override + public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + return replacePolicyTargetsInstanceId(container, prevVersion, newVersion); + } + + private ActionStatus replacePolicyTargetsInstanceId(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#replacePolicyTargetsInstanceId - replacing all policy targets for component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId()); + List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesByComponentInstanceTarget(prevVersion.getUniqueId()); + if (isEmpty(policiesWithPrevInstanceAsTarget)) { + return ActionStatus.OK; + } + replaceTargetsPrevInstanceIdWithNewInstanceId(prevVersion, newVersion, policiesWithPrevInstanceAsTarget); + return updatePolicies(container, policiesWithPrevInstanceAsTarget); + } + + private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) { + log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId()); + StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate); + return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType()); + } + + private void replaceTargetsPrevInstanceIdWithNewInstanceId(ComponentInstance prevVersion, ComponentInstance newVersion, List<PolicyDefinition> policiesWithPrevInstanceAsTarget) { + policiesWithPrevInstanceAsTarget.forEach(policy -> updatePolicyTargetWithNewInstanceVersion(policy, prevVersion.getUniqueId(), newVersion.getUniqueId())); + } + + private void updatePolicyTargetWithNewInstanceVersion(PolicyDefinition policyDefinition, String prevInstanceId, String newInstanceId) { + List<String> policyInstanceTargets = policyDefinition.resolveComponentInstanceTargets(); + if (isEmpty(policyInstanceTargets)) { + return; + } + policyInstanceTargets.replaceAll(prevInstanceIdByNewInstanceId(prevInstanceId, newInstanceId)); + } + + private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) { + return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java new file mode 100644 index 0000000000..ee16c203bf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +@FunctionalInterface +public interface PostChangeVersionOperation { + + ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java new file mode 100644 index 0000000000..ee37536886 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java @@ -0,0 +1,32 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Iterator; +import java.util.List; + +@org.springframework.stereotype.Component +public class PostChangeVersionOperationOrchestrator { + + private static final Logger log = LoggerFactory.getLogger(PostChangeVersionOperationOrchestrator.class); + private final List<PostChangeVersionOperation> postChangeVersionOperations; + + public PostChangeVersionOperationOrchestrator(List<PostChangeVersionOperation> postChangeVersionOperations) { + this.postChangeVersionOperations = postChangeVersionOperations; + } + + public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId()); + ActionStatus postOperationsResult = ActionStatus.OK; + Iterator<PostChangeVersionOperation> postChangeVersionIter = postChangeVersionOperations.iterator(); + while(postChangeVersionIter.hasNext() && postOperationsResult == ActionStatus.OK) { + postOperationsResult = postChangeVersionIter.next().onChangeVersion(container, prevVersion, newVersion); + } + return postOperationsResult; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java index 47e494f66d..c229d87593 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -45,151 +45,151 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class CertificationChangeTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class.getName()); - - private LifecycleStateEnum nextState; - private LifeCycleTransitionEnum name; - private AuditingActionEnum auditingAction; - private ArtifactsBusinessLogic artifactsManager; - - public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - this.name = name; - - // authorized roles - Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); - // TODO to be later defined for product - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.DESIGNER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - - switch (this.name) { - case CERTIFY: - this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; - this.nextState = LifecycleStateEnum.CERTIFIED; - break; - case FAIL_CERTIFICATION: - this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE; - nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; - break; - case CANCEL_CERTIFICATION: - this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE; - nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - break; - default: - break; - } - - } - - @Override - public LifeCycleTransitionEnum getName() { - return name; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return auditingAction; - } - - public ArtifactsBusinessLogic getArtifactsManager() { - return artifactsManager; - } - - public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { - this.artifactsManager = artifactsManager; - } - - private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph"); - log.debug("certification change failed on graph"); - - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return responseFormat; - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - log.error("userRoleValidation failed"); - return userValidationResponse; - } - - if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION); - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE); - log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner); - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.info("start performing certification change for resource {}", component.getUniqueId()); - Either<? extends Component, ResponseFormat> result = null; - - try { - Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); - if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - } else { - certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState); - } - - if (certificationChangeResult.isRight()) { - ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType); - result = Either.right(responseFormat); - return result; - } - - if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID()); - if (deleteOldComponentVersions.isRight()) { - ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType); - result = Either.right(responseFormat); - } - } - - result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value())); - return result; - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - - } + private static final Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class); + + private LifecycleStateEnum nextState; + private LifeCycleTransitionEnum name; + private AuditingActionEnum auditingAction; + private ArtifactsBusinessLogic artifactsManager; + + public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + this.name = name; + + // authorized roles + Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); + // TODO to be later defined for product + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + + switch (this.name) { + case CERTIFY: + this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; + this.nextState = LifecycleStateEnum.CERTIFIED; + break; + case FAIL_CERTIFICATION: + this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE; + nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; + break; + case CANCEL_CERTIFICATION: + this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE; + nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; + break; + default: + break; + } + + } + + @Override + public LifeCycleTransitionEnum getName() { + return name; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return auditingAction; + } + + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsManager; + } + + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsManager = artifactsManager; + } + + private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph"); + log.debug("certification change failed on graph"); + + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + return responseFormat; + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + log.error("userRoleValidation failed"); + return userValidationResponse; + } + + if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION); + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE); + log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner); + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.info("start performing certification change for resource {}", component.getUniqueId()); + Either<? extends Component, ResponseFormat> result = null; + + try { + Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); + if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { + certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + } else { + certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState); + } + + if (certificationChangeResult.isRight()) { + ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType); + result = Either.right(responseFormat); + return result; + } + + if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { + Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), + component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID()); + if (deleteOldComponentVersions.isRight()) { + ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType); + result = Either.right(responseFormat); + } + } + + result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value())); + return result; + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java index 4a7f446739..dfd7beeaf1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; - +import fj.data.Either; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; @@ -35,21 +28,11 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; @@ -63,289 +46,257 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.*; public class CertificationRequestTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName()); - - private CapabilityOperation capabilityOperation; - private ServiceBusinessLogic serviceBusinessLogic; - public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, - CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - // Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER, - // Role.PRODUCT_STRATEGIST}; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - // TODO to be later defined for product - // addAuthorizedRoles(ComponentTypeEnum.PRODUCT, - // Arrays.asList(productCheckoutRoles)); - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.TESTER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - - this.serviceBusinessLogic = serviceBusinessLogic; - this.capabilityOperation = capabilityOperation; - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CERTIFICATION_REQUEST; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE; - } - - protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) { - Either<Boolean, ResponseFormat> eitherResult = Either.left(true); - - List<ComponentInstance> resourceInstance = component.getComponentInstances(); - if (resourceInstance != null) { - Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny(); - // Uncertified Resource Found - if (nonCertifiedRIOptional.isPresent()) { - ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get(); - ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType()); - eitherResult = Either.right(resFormat); - } - } - return eitherResult; - } - - private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) { - - ResponseFormat responseFormat; - Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); - if (eitherResource.isRight()) { - - responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - - } else { - ActionStatus actionStatus; - Resource resource = eitherResource.left().value(); - Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource); - - if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) { - if (status.isRight() || status.left().value() == null) { - actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND; - } else { - actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; - } - } else { - if (status.isRight() || status.left().value() == null) - actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES; - else { - actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; - } - - } - String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service"; - responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName()); - } - return responseFormat; - } - - private Either<ActionStatus, Map<String, ArtifactDefinition>> validateMandatoryArtifactsSupplied(Map<String, ArtifactDefinition> artifacts) { - - if (artifacts == null || artifacts.isEmpty()) { - return Either.left(ActionStatus.OK); - } - - Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<>(); - for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = artifact.getValue(); - if (artifactDefinition.getMandatory()) { - String artifactEsId = artifactDefinition.getEsId(); - if (artifactEsId == null || artifactEsId.isEmpty()) { - invalidArtifacts.put(artifact.getKey(), artifactDefinition); - } - } - } - - if (invalidArtifacts.isEmpty()) { - return Either.left(ActionStatus.OK); - } else { - return Either.right(invalidArtifacts); - } - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing certification request for resource {}", component.getUniqueId()); - - ActionStatus actionStatus; - ResponseFormat responseFormat; - Either<? extends Component, ResponseFormat> result = null; - try{ - if (component.getToscaType().equals(ToscaElementTypeEnum.TopologyTemplate.getValue())) { - - Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); - } - - statusCert = validateConfiguredAtomicReqCapSatisfied(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); - } - } - if (componentType == ComponentTypeEnum.SERVICE) { - - Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock); - - if (generateHeatEnvResult.isRight()) { - return Either.right(generateHeatEnvResult.right().value()); - } - Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock); - if (generateVfModuleResult.isRight()) { - return Either.right(generateVfModuleResult.right().value()); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); - if (eitherPopulated != null && eitherPopulated.isRight()) { - return Either.right(eitherPopulated.right().value()); - } - - NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource; - - - Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - if (certificationRequestResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = certificationRequestResult.right().value(); - actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (!inTransaction) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (!inTransaction) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) { - log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId()); - List<ComponentInstance> componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - // Prepare relationships data structures - // Better make it list than set in case we need to count req/cap - // occurrences in the future - Map<String, List<String>> reqName2Ids = new HashMap<>(); - Map<String, List<String>> capName2Ids = new HashMap<>(); -// Either<Boolean, ResponseFormat> parseRelationsForReqCapVerificationRes = parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids); -// if(parseRelationsForReqCapVerificationRes.isRight()){ -// return parseRelationsForReqCapVerificationRes; -// } - Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert(); - Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert(); - for (ComponentInstance compInst : componentInstances) { - String compInstId = compInst.getUniqueId(); - OriginTypeEnum originType = compInst.getOriginType(); - if (originType == null) { - log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId()); - continue; - } - String compInstType = originType.getValue(); - // Validating configured requirements fulfilled - if (null != requirementsToFulfillBeforeCert) { - Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType); - if (reqToFulfillForType != null) { - for (String reqNameToFulfill : reqToFulfillForType) { - List<String> reqNameList = reqName2Ids.get(reqNameToFulfill); - if (reqNameList == null || !reqNameList.contains(compInstId)) { - log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType); - ComponentTypeEnum componentType = component.getComponentType(); - String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement", - reqNameToFulfill, "fulfilled"); - return Either.right(responseFormat); - } - } - } - } - // Validating configured capabilities consumed - if (null != capabilitiesToConsumeBeforeCert) { - Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType); - if (capToConsumeForType != null) { - for (String capNameToConsume : capToConsumeForType) { - List<String> capNameList = capName2Ids.get(capNameToConsume); - if (capNameList == null || !capNameList.contains(compInstId)) { - log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType); - ComponentTypeEnum componentType = component.getComponentType(); - String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability", - capNameToConsume, "consumed"); - return Either.right(responseFormat); - } - } - } - } - } - } - log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId()); - return Either.left(true); - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // case of "atomic" checkin and certification request - modifier must be - // the owner - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - // other states - if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class); + + private CapabilityOperation capabilityOperation; + private ServiceBusinessLogic serviceBusinessLogic; + public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, + CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + // TODO to be later defined for product + // addAuthorizedRoles(ComponentTypeEnum.PRODUCT, + // Arrays.asList(productCheckoutRoles)); + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.TESTER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + + this.serviceBusinessLogic = serviceBusinessLogic; + this.capabilityOperation = capabilityOperation; + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CERTIFICATION_REQUEST; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE; + } + + protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) { + Either<Boolean, ResponseFormat> eitherResult = Either.left(true); + + List<ComponentInstance> resourceInstance = component.getComponentInstances(); + if (resourceInstance != null) { + Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny(); + // Uncertified Resource Found + if (nonCertifiedRIOptional.isPresent()) { + ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get(); + ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType()); + eitherResult = Either.right(resFormat); + } + } + return eitherResult; + } + + private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) { + + ResponseFormat responseFormat; + Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); + if (eitherResource.isRight()) { + + responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + + } else { + ActionStatus actionStatus; + Resource resource = eitherResource.left().value(); + Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource); + + if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) { + if (status.isRight() || status.left().value() == null) { + actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND; + } else { + actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; + } + } else { + if (status.isRight() || status.left().value() == null) + actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES; + else { + actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; + } + + } + String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service"; + responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName()); + } + return responseFormat; + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing certification request for resource {}", component.getUniqueId()); + + ActionStatus actionStatus; + ResponseFormat responseFormat; + Either<? extends Component, ResponseFormat> result = null; + try{ + if (component.isTopologyTemplate()) { + + Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } + + statusCert = validateConfiguredAtomicReqCapSatisfied(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } + } + if (componentType == ComponentTypeEnum.SERVICE) { + + Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction); + + if (generateHeatEnvResult.isRight()) { + return Either.right(generateHeatEnvResult.right().value()); + } + Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction); + if (generateVfModuleResult.isRight()) { + return Either.right(generateVfModuleResult.right().value()); + } + component = generateVfModuleResult.left().value(); + + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); + if (eitherPopulated != null && eitherPopulated.isRight()) { + return Either.right(eitherPopulated.right().value()); + } + + Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (certificationRequestResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = certificationRequestResult.right().value(); + actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (!inTransaction) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (!inTransaction) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) { + log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId()); + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + // Prepare relationships data structures + // Better make it list than set in case we need to count req/cap + // occurrences in the future + Map<String, List<String>> reqName2Ids = new HashMap<>(); + Map<String, List<String>> capName2Ids = new HashMap<>(); + Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert(); + Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert(); + for (ComponentInstance compInst : componentInstances) { + String compInstId = compInst.getUniqueId(); + OriginTypeEnum originType = compInst.getOriginType(); + if (originType == null) { + log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId()); + continue; + } + String compInstType = originType.getValue(); + // Validating configured requirements fulfilled + if (null != requirementsToFulfillBeforeCert) { + Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType); + if (reqToFulfillForType != null) { + for (String reqNameToFulfill : reqToFulfillForType) { + List<String> reqNameList = reqName2Ids.get(reqNameToFulfill); + if (reqNameList == null || !reqNameList.contains(compInstId)) { + log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType); + ComponentTypeEnum componentType = component.getComponentType(); + String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement", + reqNameToFulfill, "fulfilled"); + return Either.right(responseFormat); + } + } + } + } + // Validating configured capabilities consumed + if (null != capabilitiesToConsumeBeforeCert) { + Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType); + if (capToConsumeForType != null) { + for (String capNameToConsume : capToConsumeForType) { + List<String> capNameList = capName2Ids.get(capNameToConsume); + if (capNameList == null || !capNameList.contains(compInstId)) { + log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType); + ComponentTypeEnum componentType = component.getComponentType(); + String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability", + capNameToConsume, "consumed"); + return Either.right(responseFormat); + } + } + } + } + } + } + log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId()); + return Either.left(true); + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // case of "atomic" checkin and certification request - modifier must be + // the owner + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + // other states + if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java index bfe51ded48..0d9631e6ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java @@ -20,8 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -43,106 +42,106 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class CheckinTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName()); - - public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CHECKIN; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CHECKIN_RESOURCE; - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - log.debug("start performing checkin for {} {}", componentType.name(), component.getUniqueId()); - - Either<? extends Component, ResponseFormat> result = null; - try{ - Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation. - checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - - if (checkinResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkinResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){ - action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION; - } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ - action = ActionStatus.COMPONENT_ALREADY_CERTIFIED; - } - ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CheckinTransition.class); + + public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CHECKIN; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CHECKIN_RESOURCE; + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + log.debug("start performing checkin for {} {}", componentType, component.getUniqueId()); + + Either<? extends Component, ResponseFormat> result = null; + try{ + Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation. + checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkinResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkinResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){ + action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION; + } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ + action = ActionStatus.COMPONENT_ALREADY_CERTIFIED; + } + ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index b7983b1174..e5afcaeae5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -20,9 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -32,11 +30,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; @@ -49,148 +43,149 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; public class CheckoutTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); - - public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CHECKOUT; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CHECKOUT_RESOURCE; - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId()); - - Either<? extends Component, ResponseFormat> result = null; - try { - - Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - - if (checkoutResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkoutResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } else { - - Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); - if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){ - Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); - if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ - result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); - return result; - } - if ( upgradeToLatestDerived.isLeft() ){ - //get resource after update derived - clonedComponent = upgradeToLatestDerived.left().value(); - } - } - result = Either.left(clonedComponent); - Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); - if (upgradeToLatestGeneric.isRight()) - result = Either.right(upgradeToLatestGeneric.right().value()); - else if (upgradeToLatestGeneric.left().value() ) { - StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); - if (StorageOperationStatus.OK != response) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - } - - } - - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { - - StorageOperationStatus updateStatus = StorageOperationStatus.OK; - Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); - if (updateEither.isRight()) - updateStatus = updateEither.right().value(); - else if (clonedComponent.shouldGenerateInputs()) { - List<InputDefinition> newInputs = clonedComponent.getInputs(); - updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME); - } - return updateStatus; - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // Disabled as of 1604 patch after discussing with Ella/Eli/Michael - - /* - * if (componentType == ComponentTypeEnum.PRODUCT){ Either<Boolean, ResponseFormat> productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } } - */ - - // check resource is not locked by another user - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - } - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class); + + public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CHECKOUT; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CHECKOUT_RESOURCE; + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing {} for resource {}", getName(), component.getUniqueId()); + + Either<? extends Component, ResponseFormat> result = null; + try { + + Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkoutResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkoutResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } else { + + Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); + if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){ + Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); + if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ + result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); + return result; + } + if ( upgradeToLatestDerived.isLeft() ){ + //get resource after update derived + clonedComponent = upgradeToLatestDerived.left().value(); + } + } + result = Either.left(clonedComponent); + Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); + if (upgradeToLatestGeneric.isRight()) + result = Either.right(upgradeToLatestGeneric.right().value()); + else if (upgradeToLatestGeneric.left().value() ) { + StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); + if (StorageOperationStatus.OK != response) { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + } + + } + + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { + + StorageOperationStatus updateStatus = StorageOperationStatus.OK; + Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); + if (updateEither.isRight()) + updateStatus = updateEither.right().value(); + else if (clonedComponent.shouldGenerateInputs()) { + List<InputDefinition> newInputs = clonedComponent.getInputs(); + updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME); + } + return updateStatus; + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // Disabled as of 1604 patch after discussing with Ella/Eli/Michael + + /* + * if (componentType == ComponentTypeEnum.PRODUCT){ Either<Boolean, ResponseFormat> productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } } + */ + + // check resource is not locked by another user + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { + if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + } + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java index 87e8175960..4270295e36 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -45,130 +42,129 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class LifeCycleTransition { - protected ConfigurationManager configurationManager; - @Autowired - protected ToscaElementLifecycleOperation lifeCycleOperation; - @Autowired - protected TitanDao titanDao; - protected ComponentsUtils componentUtils; - - protected Map<ComponentTypeEnum, List<Role>> authorizedRoles; - protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles; - - ToscaOperationFacade toscaOperationFacade; - - protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - - this.configurationManager = ConfigurationManager.getConfigurationManager(); - this.lifeCycleOperation = lifecycleOperation2; - this.componentUtils = componentUtils; - this.authorizedRoles = new HashMap<>(); - this.resourceAuthorizedRoles = new HashMap<>(); - this.toscaOperationFacade = toscaOperationFacade; - this.titanDao = titanDao; - } - - public abstract LifeCycleTransitionEnum getName(); - - public abstract AuditingActionEnum getAuditingAction(); - - public ConfigurationManager getConfigurationManager() { - return configurationManager; - } - - public void setConfigurationManager(ConfigurationManager configurationManager) { - this.configurationManager = configurationManager; - } - - public ToscaElementLifecycleOperation getLifeCycleOperation() { - return lifeCycleOperation; - } - - public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) { - this.lifeCycleOperation = lifeCycleOperation; - } - - public List<Role> getAuthorizedRoles(ComponentTypeEnum componentType) { - return authorizedRoles.get(componentType); - } - - public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) { - this.authorizedRoles.put(componentType, authorizedRoles); - } - - public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) { - return resourceAuthorizedRoles.get(resourceType); - } - - public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List<Role> authorizedRoles) { - this.resourceAuthorizedRoles.put(resourceType, authorizedRoles); - } - - public abstract Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction); - - public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo); - - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) { - - return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null); - } - - /** - * getComponentOwner - * - * @param resource - * @return - */ - protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType) { - - return getComponentOwner(component, componentType, false); - } - - protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) { - - Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); - if (resourceOwnerResult.isRight()) { - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); - return Either.right(responseFormat); - } - return Either.left(resourceOwnerResult.left().value()); - } - - protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - - // validate user - //first check the user for the component and then for the resource - if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) { - return Either.left(true); - } - // this is only used in 2 cases - //1. when creating vfc/cp when import vf from csar - when we - // create resources from node type, we create need to change the state - // to certified - //2. certification flow upno upgrade migration - if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) { - return Either.left(true); - } - - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - - protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) { - if (componentType.equals(ComponentTypeEnum.RESOURCE)){ - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) { - return true; - } - } else { - return false; - } - - return false; - } + protected ConfigurationManager configurationManager; + @Autowired + protected ToscaElementLifecycleOperation lifeCycleOperation; + @Autowired + protected TitanDao titanDao; + protected ComponentsUtils componentUtils; + + protected Map<ComponentTypeEnum, List<Role>> authorizedRoles; + protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles; + + ToscaOperationFacade toscaOperationFacade; + + protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + + this.configurationManager = ConfigurationManager.getConfigurationManager(); + this.lifeCycleOperation = lifecycleOperation2; + this.componentUtils = componentUtils; + this.authorizedRoles = new HashMap<>(); + this.resourceAuthorizedRoles = new HashMap<>(); + this.toscaOperationFacade = toscaOperationFacade; + this.titanDao = titanDao; + } + + public abstract LifeCycleTransitionEnum getName(); + + public abstract AuditingActionEnum getAuditingAction(); + + public ConfigurationManager getConfigurationManager() { + return configurationManager; + } + + public void setConfigurationManager(ConfigurationManager configurationManager) { + this.configurationManager = configurationManager; + } + + public ToscaElementLifecycleOperation getLifeCycleOperation() { + return lifeCycleOperation; + } + + public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) { + this.lifeCycleOperation = lifeCycleOperation; + } + + public List<Role> getAuthorizedRoles(ComponentTypeEnum componentType) { + return authorizedRoles.get(componentType); + } + + public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) { + this.authorizedRoles.put(componentType, authorizedRoles); + } + + public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) { + return resourceAuthorizedRoles.get(resourceType); + } + + public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List<Role> authorizedRoles) { + this.resourceAuthorizedRoles.put(resourceType, authorizedRoles); + } + + public abstract Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction); + + public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo); + + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) { + + return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null); + } + + /** + * getComponentOwner + * + * @param resource + * @return + */ + protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType) { + + return getComponentOwner(component, componentType, false); + } + + protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) { + + Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); + if (resourceOwnerResult.isRight()) { + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); + return Either.right(responseFormat); + } + return Either.left(resourceOwnerResult.left().value()); + } + + protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + + // validate user + //first check the user for the component and then for the resource + if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) { + return Either.left(true); + } + // this is only used in 2 cases + //1. when creating vfc/cp when import vf from csar - when we + // create resources from node type, we create need to change the state + // to certified + //2. certification flow upno upgrade migration + if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) { + return Either.left(true); + } + + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + + protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) { + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) { + return true; + } + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java index e478bc6924..75b0bd934a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - +import fj.data.Either; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -33,7 +28,6 @@ import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; @@ -56,414 +50,399 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; @org.springframework.stereotype.Component("lifecycleBusinessLogic") public class LifecycleBusinessLogic { - private static final String COMMENT = "comment"; + private static final String COMMENT = "comment"; + + @Autowired + private IGraphLockOperation graphLockOperation = null; + + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @Autowired + private TitanDao titanDao; + + @Autowired + private CapabilityOperation capabilityOperation; + + private static final Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class); - @Autowired - private IGraphLockOperation graphLockOperation = null; + @javax.annotation.Resource + private ComponentsUtils componentUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; + @javax.annotation.Resource + private ToscaElementLifecycleOperation lifecycleOperation; + @javax.annotation.Resource + ArtifactsBusinessLogic artifactsManager; - @Autowired - private TitanDao titanDao; + @javax.annotation.Resource + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Autowired - private CapabilityOperation capabilityOperation; + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; - private static Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class.getName()); + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; - @javax.annotation.Resource - private ComponentsUtils componentUtils; + @javax.annotation.Resource + private ProductBusinessLogic productBusinessLogic; - @javax.annotation.Resource - private ToscaElementLifecycleOperation lifecycleOperation; - @javax.annotation.Resource - ArtifactsBusinessLogic artifactsManager; - - @javax.annotation.Resource - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; - - @javax.annotation.Resource - private ProductBusinessLogic productBusinessLogic; - - @Autowired - private ToscaExportHandler toscaExportUtils; - - @Autowired - ICacheMangerOperation cacheManagerOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - private Map<String, LifeCycleTransition> stateTransitions; - private static volatile boolean isInitialized = false; - - @PostConstruct - public void init() { - // init parameters - if (!isInitialized) { - synchronized (this) { - if (!isInitialized) { - initStateOperations(); - isInitialized = true; - } - } - } - } - - private void initStateOperations() { - stateTransitions = new HashMap<String, LifeCycleTransition>(); - - LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(checkoutOp.getName().name(), checkoutOp); - - UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); - stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); - - LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(checkinOp.getName().name(), checkinOp); - - LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); - stateTransitions.put(certificationRequest.getName().name(), certificationRequest); - - LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(startCertification.getName().name(), startCertification); - - LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(failCertification.getName().name(), failCertification); - - LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(cancelCertification.getName().name(), cancelCertification); - - CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - successCertification.setArtifactsManager(artifactsBusinessLogic); - stateTransitions.put(successCertification.getName().name(), successCertification); - } - - public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) { - return stateTransitions.get(transitionEnum.name()); - } - - public Either<Service, ResponseFormat> changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { - return (Either<Service, ResponseFormat>) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); - } - - // TODO: rhalili - should use changeComponentState when possible - public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { - return (Either<Resource, ResponseFormat>) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); - } - - private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){ - if (componentType.equals(ComponentTypeEnum.RESOURCE)){ - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (resourceType.equals(ResourceTypeEnum.VFCMT)){ - return true; - } - } - return false; - } - - public Either<? extends Component, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, - boolean needLock) { - - LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name()); - if (lifeCycleTransition == null) { - log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(error); - } - Component component = null; - log.info("get resource from graph"); - ResponseFormat errorResponse; - - Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo); - if (eitherResourceResponse.isRight()) { - return eitherResourceResponse; - } - component = eitherResourceResponse.left().value(); - String resourceCurrVersion = component.getVersion(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - - // lock resource - if (!inTransaction && needLock) { - log.info("lock component {}", componentId); - Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component); - if (eitherLockResource.isRight()) { - errorResponse = eitherLockResource.right().value(); - componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, null); - log.error("lock component {} failed", componentId); - return Either.right(errorResponse); - } - log.debug("after lock component {}", componentId); - } - try { - Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum); - if (commentValidationResult.isRight()) { - errorResponse = commentValidationResult.right().value(); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return Either.right(errorResponse); - } - changeInfo.setUserRemarks(commentValidationResult.left().value()); - log.debug("after validate component"); - Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); - if (validateHighestVersion.isRight()) { - return Either.right(validateHighestVersion.right().value()); - } - log.debug("after validate Highest Version"); - if (isComponentVFCMT(component,componentType)){ - Either<? extends Component, ResponseFormat> changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component); - if (changeVFCMTStateResponse.isRight()){ - return changeVFCMTStateResponse; - } - } - - return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); - } finally { - component.setUniqueId(componentId); - if (!inTransaction && needLock) { - log.info("unlock component {}", componentId); - NodeTypeEnum nodeType = componentType.getNodeType(); - log.info("During change state, another component {} has been created/updated", componentId); - graphLockOperation.unlockComponent(componentId, nodeType); - - } - } - - } - - /* - * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin - * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400 - */ - private Either<? extends Component, ResponseFormat> changeVFCMTState(ComponentTypeEnum componentType, User modifier, - LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, - Component component) { - LifecycleStateEnum oldState = component.getLifecycleState(); - if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) || - transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){ - return Either.right(componentUtils.getResponseFormat( - ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName())); - } //certify is done directly from checkin - else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){ - //we will call for submit for testing first and then for certify - Either<? extends Component, ResponseFormat> actionResponse = changeState(component, - stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()), - componentType, modifier, changeInfo, inTransaction); - if (actionResponse.isRight()) { - return actionResponse; - } - actionResponse = changeState(component, - stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()), - componentType, modifier, changeInfo, inTransaction); - if (actionResponse.isRight()) { - return actionResponse; - } - } - return Either.left(null); - } - - private Either<? extends Component, ResponseFormat> changeState(Component component, LifeCycleTransition lifeCycleTransition, - ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){ - ResponseFormat errorResponse; - - LifecycleStateEnum oldState = component.getLifecycleState(); - String resourceCurrVersion = component.getVersion(); - ComponentBusinessLogic bl = getComponentBL(componentType); - - Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); - if (ownerResult.isRight()) { - return Either.right(ownerResult.right().value()); - } - User owner = ownerResult.left().value(); - log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); - - Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); - if (stateValidationResult.isRight()) { - log.error("Failed to validateBeforeTransition"); - errorResponse = stateValidationResult.right().value(); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return Either.right(errorResponse); - } - - Either<? extends Component, ResponseFormat> operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); - - if (operationResult.isRight()) { - errorResponse = operationResult.right().value(); - log.info("audit before sending error response"); - componentUtils.auditComponentAdmin(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); - - return Either.right(errorResponse); - } - Component resourceAfterOperation = operationResult.left().value(); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return operationResult; - - } - - private Either<? extends Component, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) { - - Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId); - - ResponseFormat errorResponse; - if (eitherResourceResponse.isRight()) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); - errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("audit before sending response"); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentId); - componentUtils.auditComponent(errorResponse, modifier, null, Constants.EMPTY_STRING, Constants.EMPTY_STRING, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - - return Either.right(errorResponse); - } - return Either.left(eitherResourceResponse.left().value()); - } - - private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { - ResponseFormat errorResponse; - if (!resource.isHighestVersion()) { - log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName()); - errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase()); - componentUtils.auditResource(errorResponse, modifier, resource, resource.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), null); - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateResourceNotDeleted(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { - - ResponseFormat errorResponse; - if ((resource.getIsDeleted() != null) && (resource.getIsDeleted() == true)) { - ActionStatus actionStatus = ActionStatus.RESOURCE_NOT_FOUND; - errorResponse = componentUtils.getResponseFormatByResource(actionStatus, resource.getName()); - log.debug("resource {} {} is marked for delete", resource.getName(), resource.getVersion()); - componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null); - - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) { - ResponseFormat errorResponse; - if (!component.isHighestVersion()) { - log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(), - component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase()); - componentUtils.auditComponentAdmin(errorResponse, modifier, component, component.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either<Boolean, ResponseFormat> lockComponent(ComponentTypeEnum componentType, Component component) { - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus); - ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - return Either.right(responseFormat); - } - - } - - private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { - String comment = changeInfo.getUserRemarks(); - if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum - || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum - // import? - ) { - - if (!ValidationUtils.validateStringNotEmpty(comment)) { - log.debug("user comment cannot be empty or null."); - ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT); - return Either.right(errorResponse); - } - - comment = ValidationUtils.removeNoneUtf8Chars(comment); - comment = ValidationUtils.removeHtmlTags(comment); - comment = ValidationUtils.normaliseWhitespace(comment); - comment = ValidationUtils.stripOctets(comment); - - if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) { - log.debug("user comment exceeds limit."); - return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); - } - if (!ValidationUtils.validateIsEnglish(comment)) { - return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - return Either.left(comment); - } - - private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) { - ComponentBusinessLogic businessLogic; - switch (componentTypeEnum) { - case RESOURCE: { - businessLogic = this.resourceBusinessLogic; - break; - } - case SERVICE: { - businessLogic = this.serviceBusinessLogic; - break; - } - case PRODUCT: { - businessLogic = this.productBusinessLogic; - break; - } - - default: { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); - throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); - } - } - return businessLogic; - } - - public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) { - - Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid); - - if (latestVersionEither.isRight()) { - - return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid)); - } - - Component latestComponent = latestVersionEither.left().value(); - - return Either.left(latestComponent); - } + @Autowired + private ToscaExportHandler toscaExportUtils; + + @Autowired + ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + private Map<String, LifeCycleTransition> stateTransitions; + private static volatile boolean isInitialized = false; + + @PostConstruct + public void init() { + // init parameters + if (!isInitialized) { + synchronized (this) { + if (!isInitialized) { + initStateOperations(); + isInitialized = true; + } + } + } + } + + private void initStateOperations() { + stateTransitions = new HashMap<String, LifeCycleTransition>(); + + LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(checkoutOp.getName().name(), checkoutOp); + + UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); + stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); + + LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(checkinOp.getName().name(), checkinOp); + + LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); + stateTransitions.put(certificationRequest.getName().name(), certificationRequest); + + LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(startCertification.getName().name(), startCertification); + + LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(failCertification.getName().name(), failCertification); + + LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(cancelCertification.getName().name(), cancelCertification); + + CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + successCertification.setArtifactsManager(artifactsBusinessLogic); + stateTransitions.put(successCertification.getName().name(), successCertification); + } + + public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) { + return stateTransitions.get(transitionEnum.name()); + } + + public Either<Service, ResponseFormat> changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { + return (Either<Service, ResponseFormat>) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); + } + + // TODO: rhalili - should use changeComponentState when possible + public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { + return (Either<Resource, ResponseFormat>) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); + } + + private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){ + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (resourceType.equals(ResourceTypeEnum.VFCMT)){ + return true; + } + } + return false; + } + + public Either<? extends Component, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, + boolean needLock) { + + LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name()); + if (lifeCycleTransition == null) { + log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); + ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier,componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(error); + } + Component component = null; + log.info("get resource from graph"); + ResponseFormat errorResponse; + + Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo); + if (eitherResourceResponse.isRight()) { + return eitherResourceResponse; + } + component = eitherResourceResponse.left().value(); + String resourceCurrVersion = component.getVersion(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + + // lock resource + if (!inTransaction && needLock) { + log.info("lock component {}", componentId); + Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component); + if (eitherLockResource.isRight()) { + errorResponse = eitherLockResource.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build()); + + log.error("lock component {} failed", componentId); + return Either.right(errorResponse); + } + log.debug("after lock component {}", componentId); + } + try { + Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum); + if (commentValidationResult.isRight()) { + errorResponse = commentValidationResult.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder() + .state(resourceCurrState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks()); + return Either.right(errorResponse); + } + changeInfo.setUserRemarks(commentValidationResult.left().value()); + log.debug("after validate component"); + Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); + if (validateHighestVersion.isRight()) { + return Either.right(validateHighestVersion.right().value()); + } + log.debug("after validate Highest Version"); + if (isComponentVFCMT(component,componentType)){ + Either<? extends Component, ResponseFormat> changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, true, component); + if (changeVFCMTStateResponse.isRight()){ + return changeVFCMTStateResponse; + } + component = changeVFCMTStateResponse.left().value(); + } + return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); + } finally { + component.setUniqueId(componentId); + if (!inTransaction && needLock) { + log.info("unlock component {}", componentId); + NodeTypeEnum nodeType = componentType.getNodeType(); + log.info("During change state, another component {} has been created/updated", componentId); + graphLockOperation.unlockComponent(componentId, nodeType); + + } + } + + } + + /* + * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin + * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400 + */ + private Either<? extends Component, ResponseFormat> changeVFCMTState(ComponentTypeEnum componentType, User modifier, + LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, + Component component) { + LifecycleStateEnum oldState = component.getLifecycleState(); + Component updatedComponent = component; + if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) || + transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){ + return Either.right(componentUtils.getResponseFormat( + ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName())); + } //certify is done directly from checkin + else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){ + //we will call for submit for testing first and then for certify + Either<? extends Component, ResponseFormat> actionResponse = changeState(component, + stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; + } + updatedComponent = actionResponse.left().value(); + actionResponse = changeState(updatedComponent, + stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; + } + updatedComponent = actionResponse.left().value(); + + } + return Either.left(updatedComponent); + } + + private Either<? extends Component, ResponseFormat> changeState(Component component, LifeCycleTransition lifeCycleTransition, + ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){ + ResponseFormat errorResponse; + + LifecycleStateEnum oldState = component.getLifecycleState(); + String resourceCurrVersion = component.getVersion(); + ComponentBusinessLogic bl = getComponentBL(componentType); + + Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); + if (ownerResult.isRight()) { + return Either.right(ownerResult.right().value()); + } + User owner = ownerResult.left().value(); + log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); + + Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); + if (stateValidationResult.isRight()) { + log.error("Failed to validateBeforeTransition"); + errorResponse = stateValidationResult.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().version(resourceCurrVersion).state(oldState.name()).build(), changeInfo.getUserRemarks()); + return Either.right(errorResponse); + } + + Either<? extends Component, ResponseFormat> operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); + + if (operationResult.isRight()) { + errorResponse = operationResult.right().value(); + log.info("audit before sending error response"); + componentUtils.auditComponentAdmin(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build()); + + return Either.right(errorResponse); + } + Component resourceAfterOperation = operationResult.left().value(); + componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks()); + return operationResult; + + } + + private Either<? extends Component, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) { + + Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId); + + ResponseFormat errorResponse; + if (eitherResourceResponse.isRight()) { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); + errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("audit before sending response"); + componentUtils.auditComponent(errorResponse, modifier, lifeCycleTransition.getAuditingAction(), componentId, componentType, changeInfo.getUserRemarks()); + + return Either.right(errorResponse); + } + return Either.left(eitherResourceResponse.left().value()); + } + + private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { + ResponseFormat errorResponse; + if (!resource.isHighestVersion()) { + log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName()); + errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase()); + componentUtils.auditResource(errorResponse, modifier, resource, lifeCycleTransition.getAuditingAction(), ResourceAuditData.newBuilder() + .state(resource.getLifecycleState().name()).version(resourceCurrVersion).build()); + return Either.right(errorResponse); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) { + ResponseFormat errorResponse; + if (!component.isHighestVersion()) { + log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(), + component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase()); + componentUtils.auditComponentAdmin(errorResponse, modifier, component,lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(resourceCurrVersion).build()); + return Either.right(errorResponse); + } + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> lockComponent(ComponentTypeEnum componentType, Component component) { + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus); + ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + return Either.right(responseFormat); + } + + } + + private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { + String comment = changeInfo.getUserRemarks(); + if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum + || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum + // import? + ) { + + if (!ValidationUtils.validateStringNotEmpty(comment)) { + log.debug("user comment cannot be empty or null."); + ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT); + return Either.right(errorResponse); + } + + comment = ValidationUtils.removeNoneUtf8Chars(comment); + comment = ValidationUtils.removeHtmlTags(comment); + comment = ValidationUtils.normaliseWhitespace(comment); + comment = ValidationUtils.stripOctets(comment); + + if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) { + log.debug("user comment exceeds limit."); + return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); + } + if (!ValidationUtils.validateIsEnglish(comment)) { + return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + return Either.left(comment); + } + + private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) { + ComponentBusinessLogic businessLogic; + switch (componentTypeEnum) { + case RESOURCE: + businessLogic = this.resourceBusinessLogic; + break; + case SERVICE: + businessLogic = this.serviceBusinessLogic; + break; + case PRODUCT: + businessLogic = this.productBusinessLogic; + break; + default: + throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); + } + return businessLogic; + } + + public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) { + + Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid); + + if (latestVersionEither.isRight()) { + + return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid)); + } + + Component latestComponent = latestVersionEither.left().value(); + + return Either.left(latestComponent); + } /** * Performs Force certification. * Note that a Force certification is allowed for the first certification only, @@ -476,59 +455,59 @@ public class LifecycleBusinessLogic { * @param needLock * @return */ - public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - Either<Resource, ResponseFormat> result = null; - Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null; - if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){ - log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction().name()); - result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - if(!isFirstCertification(resource.getVersion())){ - log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName()); - result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - // lock resource - if(result == null && !inTransaction && needLock){ - log.info("lock component {}", resource.getUniqueId()); - Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource); - if (eitherLockResource.isRight()) { - log.error("lock component {} failed", resource.getUniqueId()); - result = Either.right(eitherLockResource.right().value()); - } - log.info("after lock component {}", resource.getUniqueId()); - } - try{ - if(result == null){ - certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion()); - if (certifyResourceRes.isRight()) { - StorageOperationStatus status = certifyResourceRes.right().value(); - log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status); - result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); - } - } - if(result == null){ - result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value())); - } - } finally { - log.info("unlock component {}", resource.getUniqueId()); - if (!inTransaction) { - if(result.isLeft()){ - titanDao.commit(); - } else{ - titanDao.rollback(); - } - if(needLock){ - NodeTypeEnum nodeType = resource.getComponentType().getNodeType(); - log.info("During change state, another component {} has been created/updated", resource.getUniqueId()); - graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType); - } - } - } - return result; - } - - public boolean isFirstCertification(String previousVersion) { - return previousVersion.split("\\.")[0].equals("0"); - } + public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + Either<Resource, ResponseFormat> result = null; + Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null; + if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){ + log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction()); + result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + if(!isFirstCertification(resource.getVersion())){ + log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName()); + result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + // lock resource + if(result == null && !inTransaction && needLock){ + log.info("lock component {}", resource.getUniqueId()); + Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource); + if (eitherLockResource.isRight()) { + log.error("lock component {} failed", resource.getUniqueId()); + result = Either.right(eitherLockResource.right().value()); + } + log.info("after lock component {}", resource.getUniqueId()); + } + try{ + if(result == null){ + certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion()); + if (certifyResourceRes.isRight()) { + StorageOperationStatus status = certifyResourceRes.right().value(); + log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status); + result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); + } + } + if(result == null){ + result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value())); + } + } finally { + log.info("unlock component {}", resource.getUniqueId()); + if (!inTransaction) { + if(result.isLeft()){ + titanDao.commit(); + } else{ + titanDao.rollback(); + } + if(needLock){ + NodeTypeEnum nodeType = resource.getComponentType().getNodeType(); + log.info("During change state, another component {} has been created/updated", resource.getUniqueId()); + graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType); + } + } + } + return result; + } + + public boolean isFirstCertification(String previousVersion) { + return previousVersion.split("\\.")[0].equals("0"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java index 0c35caf41b..dcce9b002c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java @@ -22,21 +22,21 @@ package org.openecomp.sdc.be.components.lifecycle; public class LifecycleChangeInfoBase { - public LifecycleChangeInfoBase() { - } + public LifecycleChangeInfoBase() { + } - public LifecycleChangeInfoBase(String userRemarks) { - super(); - this.userRemarks = userRemarks; - } + public LifecycleChangeInfoBase(String userRemarks) { + super(); + this.userRemarks = userRemarks; + } - private String userRemarks; + private String userRemarks; - public String getUserRemarks() { - return userRemarks; - } + public String getUserRemarks() { + return userRemarks; + } - public void setUserRemarks(String userRemarks) { - this.userRemarks = userRemarks; - } + public void setUserRemarks(String userRemarks) { + this.userRemarks = userRemarks; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java index 5d8b29ecdc..51ec61ea6b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java @@ -22,29 +22,29 @@ package org.openecomp.sdc.be.components.lifecycle; public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase { - public enum LifecycleChanceActionEnum { - CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION - }; + public enum LifecycleChanceActionEnum { + CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION + }; - private LifecycleChanceActionEnum action; + private LifecycleChanceActionEnum action; - public LifecycleChangeInfoWithAction() { - } + public LifecycleChangeInfoWithAction() { + } - public LifecycleChangeInfoWithAction(String userRemarks) { - super(userRemarks); - } + public LifecycleChangeInfoWithAction(String userRemarks) { + super(userRemarks); + } - public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) { - super(userRemarks); - this.action = action; - } + public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) { + super(userRemarks); + this.action = action; + } - public LifecycleChanceActionEnum getAction() { - return action; - } + public LifecycleChanceActionEnum getAction() { + return action; + } - public void setAction(LifecycleChanceActionEnum action) { - this.action = action; - } + public void setAction(LifecycleChanceActionEnum action) { + this.action = action; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java index b74ae5d8e5..4dddc044f2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java @@ -48,97 +48,97 @@ import fj.data.Either; public class StartCertificationTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName()); - - public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles)); - // TODO to be later defined for product - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.DESIGNER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.START_CERTIFICATION; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.START_CERTIFICATION_RESOURCE; - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing certification test for resource {}", component.getUniqueId()); - Either<? extends Component, ResponseFormat> result = null; - try{ - Either<ToscaElement, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - if (stateChangeResult.isRight()) { - log.debug("start certification failed on graph"); - StorageOperationStatus response = stateChangeResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(StartCertificationTransition.class); + + public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles)); + // TODO to be later defined for product + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.START_CERTIFICATION; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.START_CERTIFICATION_RESOURCE; + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing certification test for resource {}", component.getUniqueId()); + Either<? extends Component, ResponseFormat> result = null; + try{ + Either<ToscaElement, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (stateChangeResult.isRight()) { + log.debug("start certification failed on graph"); + StorageOperationStatus response = stateChangeResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java index 324e46016f..9444faa27a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -44,97 +44,97 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class UndoCheckoutTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); - private ArtifactsBusinessLogic artifactsManager; - - public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.UNDO_CHECKOUT; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE; - } - - public ArtifactsBusinessLogic getArtifactsBusinessLogic() { - return artifactsManager; - } - - public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) { - this.artifactsManager = artifactsBusinessLogic; - } - - @Override - public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // check resource is not locked by another user - if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } - - @Override - public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - Either<? extends Component, ResponseFormat> result = null; - log.debug("start performing undo-checkout for resource {}", component.getUniqueId()); - - try { - Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId()); - - if (undoCheckoutResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = undoCheckoutResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - return result; - } + private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class); + private ArtifactsBusinessLogic artifactsManager; + + public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.UNDO_CHECKOUT; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE; + } + + public ArtifactsBusinessLogic getArtifactsBusinessLogic() { + return artifactsManager; + } + + public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) { + this.artifactsManager = artifactsBusinessLogic; + } + + @Override + public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // check resource is not locked by another user + if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } + + @Override + public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + Either<? extends Component, ResponseFormat> result = null; + log.debug("start performing undo-checkout for resource {}", component.getUniqueId()); + + try { + Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId()); + + if (undoCheckoutResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = undoCheckoutResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java index 9c140b36c7..e6dd6457cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java @@ -1,9 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -12,7 +9,9 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; @Component public class GlobalInputsFilteringBusinessLogic extends BaseBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java index eb359e949e..4bd799805f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -11,7 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; @Component public class GlobalTypesMergeBusinessLogic implements MergeResourceBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java index 6c20e501f9..058d4c2555 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @Component public class RelationsComparator { @@ -45,8 +45,8 @@ public class RelationsComparator { private boolean findRelation(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) { for (RequirementCapabilityRelDef oldRelation : oldRelations) { - RelationshipInfo oldRelationship = oldRelation.getSingleRelationship().getRelation(); - RelationshipInfo newRelationship = newRelation.getSingleRelationship().getRelation(); + RelationshipInfo oldRelationship = oldRelation.resolveSingleRelationship().getRelation(); + RelationshipInfo newRelationship = newRelation.resolveSingleRelationship().getRelation(); if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) { return true; } @@ -70,12 +70,12 @@ public class RelationsComparator { private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){ - return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); + return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); } else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){ - return true; + return true; } - return false; + return false; } private boolean isRelationshipTypeEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { @@ -84,12 +84,12 @@ public class RelationsComparator { private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){ - return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); + return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); } else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){ - return true; + return true; } - return false; + return false; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java index 8b48b0897a..0f68f9f409 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.exception.SdcActionException; @@ -15,7 +13,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component public class TopologyComparator { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java new file mode 100644 index 0000000000..0a467ef876 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +import java.util.List; +import java.util.Map; + +public interface CapabilityResolver { + + /** + * + * @param container the instance container + * @param prevInstanceOrigNode the prev instance's original node type + * @param cmptInstanceId the current instance id + * @param prevCapabilities list of previous capabilities for which to find their corresponding new capabilities + * @return a mapping between the prev capability to its corresponding new capability (if exists) + */ + Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities); + + /** + * + * @param oldInstance the old instance of which its capabilities are to be mapped as the key + * @param currInstance the curr instance of which its capabilities are to be mapped as the value + * @return a mapping between the prev capability to its corresponding new capability (if exists) + */ + Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java new file mode 100644 index 0000000000..8400b32f9b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java @@ -0,0 +1,82 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component +public class SimpleCapabilityResolver implements CapabilityResolver { + + private MergeInstanceUtils mergeInstanceUtils; + + public SimpleCapabilityResolver(MergeInstanceUtils mergeInstanceUtils) { + this.mergeInstanceUtils = mergeInstanceUtils; + } + + @Override + public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) { + Map<String, List<CapabilityDefinition>> newCapabilitiesByType = resolveInstanceCapabilities(container, cmptInstanceId).getCapabilities(); + Map<String, String> oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, prevCapabilities); + return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner); + } + + @Override + public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance) { + Map<String, List<CapabilityDefinition>> newCapabilitiesByType = currInstance.getCapabilities(); + Map<String, String> oldCapOwnerToNewOwner = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance); + List<CapabilityDefinition> prevCapabilities = oldInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner); + } + + private Map<CapabilityDefinition, CapabilityDefinition> mapOldToNewCapabilities(List<CapabilityDefinition> prevCapabilities, Map<String, List<CapabilityDefinition>> newCapabilitiesByType, Map<String, String> oldCapOwnerToNewOwner) { + Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapability = prevCapabilities + .stream() + .collect(HashMap::new, + (resultMap, prevCap) -> mapOldToNewCapability(newCapabilitiesByType, oldCapOwnerToNewOwner, resultMap, prevCap), + HashMap::putAll); + removeNotFoundNewCapabilities(oldToNewCapability); + return oldToNewCapability; + } + + private CapabilityDefinition mapOldToNewCapability(Map<String, List<CapabilityDefinition>> newCapabilitiesByType, Map<String, String> oldCapOwnerToNewOwner, Map<CapabilityDefinition, CapabilityDefinition> resultMap, CapabilityDefinition prevCap) { + return resultMap.put(prevCap, findCurrCapability(newCapabilitiesByType, prevCap, oldCapOwnerToNewOwner.get(prevCap.getOwnerId()))); + } + + private Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) { + List<String> prevCapOwnerIds = prevCapabilities.stream().map(CapabilityDefinition::getOwnerId).distinct().collect(Collectors.toList()); + return mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, origInstanceNode, cmptInstanceId, prevCapOwnerIds); + } + + private void removeNotFoundNewCapabilities(Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapMap) { + oldToNewCapMap.values().removeIf(Objects::isNull); + } + + private ComponentInstance resolveInstanceCapabilities(Component capabilityOwnerContainer, String cmptInstanceId) { + return MapUtil.toMap(capabilityOwnerContainer.getComponentInstances(), ComponentInstance::getUniqueId).get(cmptInstanceId); + } + + + private CapabilityDefinition findCurrCapability(Map<String, List<CapabilityDefinition>> capabilitiesByType, CapabilityDefinition oldCap, String newCapOwnerId) { + List<CapabilityDefinition> newCapOfType = capabilitiesByType.get(oldCap.getType()); + if (newCapOwnerId == null || CollectionUtils.isEmpty(newCapOfType)) { + return null; + } + return newCapOfType.stream().filter(sameNameAndOwner(oldCap.getName(), newCapOwnerId)) + .findFirst().orElse(null); + + } + + private Predicate<CapabilityDefinition> sameNameAndOwner(String capName, String newCapOwnerId) { + return newCap -> newCap.getName().equals(capName) && newCap.getOwnerId().equals(newCapOwnerId); + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java index 1e1bc862cf..82deee598d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge.heat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * Created by chaya on 9/14/2017. */ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java index b8ea5e35c4..be5e5367b8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java @@ -1,9 +1,7 @@ package org.openecomp.sdc.be.components.merge.input; -import java.util.Collections; -import java.util.List; -import java.util.Map; - +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -12,10 +10,13 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component -public class ComponentInputsMergeBL { +public class ComponentInputsMergeBL implements ComponentsMergeCommand { @javax.annotation.Resource private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic; @@ -26,6 +27,17 @@ public class ComponentInputsMergeBL { @javax.annotation.Resource private ComponentsUtils componentsUtils; + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + List<InputDefinition> inputsToMerge = currentComponent.getInputs() != null ? currentComponent.getInputs() : new ArrayList<>(); + return this.mergeAndRedeclareComponentInputs(prevComponent, currentComponent, inputsToMerge); + } + + @Override + public String description() { + return "merge component inputs"; + } + public ActionStatus mergeAndRedeclareComponentInputs(Component prevComponent, Component newComponent, List<InputDefinition> inputsToMerge) { mergeInputs(prevComponent, inputsToMerge); List<InputDefinition> previouslyDeclaredInputs = inputsValuesMergingBusinessLogic.getPreviouslyDeclaredInputsToMerge(prevComponent, newComponent); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java index e49d2b2c87..e0e7947226 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java @@ -1,12 +1,5 @@ package org.openecomp.sdc.be.components.merge.input; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; @@ -14,6 +7,9 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.*; +import java.util.stream.Collectors; + @org.springframework.stereotype.Component public class InputsValuesMergingBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java new file mode 100644 index 0000000000..e7117a2aeb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java @@ -0,0 +1,103 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.merge.capability.CapabilityResolver; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class ComponentCapabilitiesPropertiesMergeBL implements ComponentsMergeCommand { + + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentCapabilitiesPropertiesMergeBL.class); + + private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; + private ToscaOperationFacade toscaOperationFacade; + private ComponentsUtils componentsUtils; + private CapabilityResolver capabilityResolver; + + public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, CapabilityResolver capabilityResolver) { + this.dataDefinitionsValuesMergingBusinessLogic = dataDefinitionsValuesMergingBusinessLogic; + this.toscaOperationFacade = toscaOperationFacade; + this.componentsUtils = componentsUtils; + this.capabilityResolver = capabilityResolver; + } + + @Override + public String description() { + return "merge component instances capabilities properties"; + } + + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + StorageOperationStatus mergeStatus = getCmptWithCapabilitiesProps(currentComponent.getUniqueId()) + .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap), + err -> err); + return componentsUtils.convertFromStorageResponse(mergeStatus); + } + + public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId, List<CapabilityDefinition> prevInstanceCapabilities) { + if (CollectionUtils.isEmpty(prevInstanceCapabilities)) { + return ActionStatus.OK; + } + Map<CapabilityDefinition, CapabilityDefinition> oldToNewCap = capabilityResolver.resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities); + oldToNewCap.forEach(this::mergeCapabilityProperties); + StorageOperationStatus updateStatus = updateInstanceCapabilitiesProperties(currentComponent, instanceId); + return componentsUtils.convertFromStorageResponse(updateStatus); + } + + private StorageOperationStatus mergeCmptCalculatedCapabilitiesProperties(Component prevComponent, Component currentComponent) { + List<ComponentInstance> prevInstances = prevComponent.getComponentInstances(); + if (prevInstances == null) { + return StorageOperationStatus.OK; + } + prevInstances.forEach(prevInstance -> mergeInstanceCapabilities(prevInstance, currentComponent)); + return updateComponentCapabilitiesProperties(currentComponent); + } + + private void mergeInstanceCapabilities(ComponentInstance prevInstance, Component currComponent) { + ComponentInstance currInstance = MapUtil.toMap(currComponent.getComponentInstances(), ComponentInstance::getName).get(prevInstance.getName()); + Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapabilities = capabilityResolver.resolvePrevCapIdToNewCapability(prevInstance, currInstance); + oldToNewCapabilities.forEach(this::mergeCapabilityProperties); + } + + private void mergeCapabilityProperties(CapabilityDefinition prevCapability, CapabilityDefinition currCapability) { + dataDefinitionsValuesMergingBusinessLogic.mergeInstanceDataDefinitions(prevCapability.getProperties(), currCapability.getProperties()); + } + + private StorageOperationStatus updateComponentCapabilitiesProperties(Component currComponent) { + return toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currComponent); + } + + private StorageOperationStatus updateInstanceCapabilitiesProperties(Component currComponent, String instanceId) { + return toscaOperationFacade.updateComponentInstanceCapabilityProperties(currComponent, instanceId); + } + + private Either<Component, StorageOperationStatus> getCmptWithCapabilitiesProps(String cmptId) { + ComponentParametersView propertiesCapabilitiesFilter = new ComponentParametersView(true); + propertiesCapabilitiesFilter.setIgnoreCapabiltyProperties(false); + propertiesCapabilitiesFilter.setIgnoreComponentInstances(false); + propertiesCapabilitiesFilter.setIgnoreCapabilities(false); + return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter) + .right() + .map(err -> { + LOGGER.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err); + return err; + }); + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java index cac8c977e3..d16fa251e2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java @@ -1,10 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -16,7 +12,10 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; /** * Created by chaya on 9/20/2017. @@ -81,7 +80,7 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, jsonForUpdateArtifact, artifactsBusinessLogic.new ArtifactOperationInfo( - false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Link), currentArtifactDefinition.getValue()); + false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue()); if (uploadArtifactToService.isRight()) { return Either.right(uploadArtifactToService.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java new file mode 100644 index 0000000000..afad19baf2 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java @@ -0,0 +1,47 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.MapUtils.isNotEmpty; + +@org.springframework.stereotype.Component +public class ComponentInstanceCapabiliteisPropertiesMerge implements ComponentInstanceMergeInterface { + + private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; + private ComponentsUtils componentsUtils; + + public ComponentInstanceCapabiliteisPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, ComponentsUtils componentsUtils) { + this.capabilitiesPropertiesMergeBL = capabilitiesPropertiesMergeBL; + this.componentsUtils = componentsUtils; + } + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); + dataHolder.setOrigInstanceNode(originComponent); + } + + @Override + public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Component origInstanceNode = dataHolder.getOrigInstanceNode(); + List<CapabilityDefinition> origInstanceCapabilities = dataHolder.getOrigInstanceCapabilities(); + ActionStatus mergeStatus = capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities); + return Either.iif(!ActionStatus.OK.equals(mergeStatus), () -> componentsUtils.getResponseFormat(mergeStatus), () -> updatedContainerComponent); + } + + private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { + return isNotEmpty( currentResourceInstance.getCapabilities() ) ? currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) : new ArrayList<>() ; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java new file mode 100644 index 0000000000..20a5abc591 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java @@ -0,0 +1,113 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.javatuples.Pair; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component +public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMergeInterface { + + private static Logger log = LoggerFactory.getLogger(ComponentInstanceForwardingPathMerge.class); + + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Autowired + private ComponentsUtils componentsUtils; + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, + ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); + dataHolder.setOrigInstanceNode(originComponent); + dataHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId()); + } + + @Override + public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, + Component updatedContainerComponent, String newInstanceId) { + if (!(updatedContainerComponent instanceof Service)) { + // no need to handle forwarding paths + return Either.left(updatedContainerComponent); + } + Service service = (Service) updatedContainerComponent; + ComponentInstance ci = service.getComponentInstanceById(newInstanceId).orElse(null); + if (ci == null){ + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, newInstanceId); + return Either.right(responseFormat); + } + Either<Component, StorageOperationStatus> resourceEither = toscaOperationFacade.getToscaFullElement(ci.getComponentUid()); + if (resourceEither.isRight() ) { + log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value())); + return Either.right(responseFormat); + } + + Component fetchedComponent = resourceEither.left().value(); + + Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service, dataHolder, fetchedComponent, newInstanceId); + Map<String, ForwardingPathDataDefinition> updated = pair.getValue0(); + Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1(); + if (deleted != null && !deleted.isEmpty()) { + Either<Set<String>, ResponseFormat> deleteEither = serviceBusinessLogic + .deleteForwardingPaths(service.getUniqueId(), new HashSet<>(deleted.keySet()), user, false); + if (deleteEither.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Failed to delete forwarding paths : {}", deleted.values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )"))); + } + return Either.right(deleteEither.right().value()); + } + deleted.keySet().forEach(key -> service.getForwardingPaths().remove(key)); + } + if (updated != null && !updated.isEmpty()) { + Service updateFPService = new Service(); + updateFPService.setForwardingPaths(updated); + Either<Service, ResponseFormat> updateFPEither = serviceBusinessLogic + .updateForwardingPath(service.getUniqueId(), updateFPService, user, false); + if (updateFPEither.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Failed to update forwarding paths : {}", updated.values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )"))); + } + return Either.right(updateFPEither.right().value()); + } + updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key,forwardingPathDataDefinition)); + } + return Either.left(updatedContainerComponent); + } + + + private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { + return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java index 1561cdc797..3938281ad2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -17,7 +15,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.List; +import java.util.Map; /** * Created by chaya on 9/20/2017. @@ -25,7 +24,7 @@ import fj.data.Either; @org.springframework.stereotype.Component("ComponentInstanceHeatEnvMerge") public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class); @Autowired private ArtifactsBusinessLogic artifactsBusinessLogic; @@ -52,7 +51,7 @@ public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInte Map<String, Object> json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null); Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json, - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update), null); + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE), null); if (uploadArtifactToService.isRight()) { log.error("Failed to update artifact {} on resourceInstance {}", artifactInfo.getArtifactLabel(), newInstanceId); return Either.right(uploadArtifactToService.right().value()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java index 4e49eef94c..2e289456e6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java @@ -1,9 +1,7 @@ -package org.openecomp.sdc.be.components.merge.property; - -import java.util.Collections; -import java.util.List; -import java.util.Map; +package org.openecomp.sdc.be.components.merge.instance; +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; @@ -13,10 +11,12 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component -public class ComponentInstanceInputsMergeBL { +public class ComponentInstanceInputsMergeBL implements ComponentsMergeCommand { @javax.annotation.Resource private ToscaOperationFacade toscaOperationFacade; @@ -27,13 +27,19 @@ public class ComponentInstanceInputsMergeBL { @javax.annotation.Resource private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - public ActionStatus mergeComponentInstancesInputs(Component oldComponent, Component newComponent) { - Map<String, List<ComponentInstanceInput>> componentInstancesInputs = newComponent.getComponentInstancesInputs(); + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = currentComponent.getComponentInstancesInputs(); if (componentInstancesInputs == null) { return ActionStatus.OK; } - componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(oldComponent, newComponent, instanceId, instInputs)); - return updateComponentInstancesInputs(newComponent, componentInstancesInputs); + componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs)); + return updateComponentInstancesInputs(currentComponent, componentInstancesInputs); + } + + @Override + public String description() { + return "merge component instance inputs"; } public ActionStatus mergeComponentInstanceInputs(List<ComponentInstanceInput> oldInstProps, List<InputDefinition> oldInputs, Component newComponent, String instanceId) { @@ -68,5 +74,4 @@ public class ComponentInstanceInputsMergeBL { propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs()); } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java index 04af6b7fc0..d17469a287 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; @@ -15,14 +14,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.List; /** * Created by chaya on 9/12/2017. */ @org.springframework.stereotype.Component("componentInstanceMergeDataBusinessLogic") public class ComponentInstanceMergeDataBusinessLogic { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class); @Autowired private List<ComponentInstanceMergeInterface> componentInstancesMergeBLs; @@ -60,7 +59,7 @@ public class ComponentInstanceMergeDataBusinessLogic { */ public Either<Component, ResponseFormat> mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) { - Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); + Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { log.error("Component with id {} was not found", newContainerComponentId); StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value(); @@ -79,12 +78,15 @@ public class ComponentInstanceMergeDataBusinessLogic { return Either.left(updatedContainerComponent); } - private Either<Component, StorageOperationStatus> getComponentWithInstancesInputsAndProperties(String containerComponentId) { + private Either<Component, StorageOperationStatus> getComponentWithInstancesMergeEntities(String containerComponentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); filter.setIgnoreComponentInstancesInputs(false); filter.setIgnoreComponentInstancesProperties(false); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); filter.setIgnoreArtifacts(false); + filter.setIgnoreForwardingPath(false); return toscaOperationFacade.getToscaElement(containerComponentId, filter); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java index 1d2849b94c..f4bcfdab5c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java @@ -1,12 +1,11 @@ package org.openecomp.sdc.be.components.merge.instance; +import fj.data.Either; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; - /** * Created by chaya on 9/20/2017. */ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java index 43e3ec624a..99b1d389ed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java @@ -1,22 +1,21 @@ -package org.openecomp.sdc.be.components.merge.property; - -import java.util.Collections; -import java.util.List; -import java.util.Map; +package org.openecomp.sdc.be.components.merge.instance; +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component -public class ComponentInstancePropertiesMergeBL { +public class ComponentInstancePropertiesMergeBL implements ComponentsMergeCommand { @javax.annotation.Resource private ToscaOperationFacade toscaOperationFacade; @@ -27,13 +26,19 @@ public class ComponentInstancePropertiesMergeBL { @javax.annotation.Resource private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - public ActionStatus mergeComponentInstancesProperties(Component oldComponent, Resource newResource) { - Map<String, List<ComponentInstanceProperty>> newInstProps = newResource.getComponentInstancesProperties(); + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + Map<String, List<ComponentInstanceProperty>> newInstProps = currentComponent.getComponentInstancesProperties(); if (newInstProps == null) { return ActionStatus.OK; } - newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(oldComponent, newResource, instanceId, newProps) ); - return updateComponentInstancesProperties(newResource, newInstProps); + newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(prevComponent, currentComponent, instanceId, newProps) ); + return updateComponentInstancesProperties(currentComponent, newInstProps); + } + + @Override + public String description() { + return "merge component instance properties"; } @@ -68,6 +73,4 @@ public class ComponentInstancePropertiesMergeBL { return ActionStatus.OK; } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java index 765ddb57f6..b63cc38690 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java @@ -1,20 +1,10 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; @@ -22,7 +12,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; /** * Created by chaya on 9/20/2017. @@ -30,7 +21,7 @@ import fj.data.Either; @org.springframework.stereotype.Component("ComponentInstancePropsAndInputsMerge") public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface { - private static Logger log = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class); @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -81,19 +72,19 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId); if (actionStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps); + LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps); return Either.right(actionStatus); } return Either.left(newComponentInstancesProps); } private Either<List<ComponentInstanceInput>, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { - List<ComponentInstanceInput> originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); + List<ComponentInstanceInput> originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); List<InputDefinition> originComponentsInputs = dataHolder.getOrigComponentInputs(); List<ComponentInstanceInput> newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId); ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId); if (actionStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs); + LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs); return Either.right(actionStatus); } return Either.left(newComponentInstancesInputs); @@ -106,14 +97,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe // get instance inputs and properties after merge Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { - log.error("Component %s was not found", newContainerComponentId); + LOGGER.error("Component %s was not found", newContainerComponentId); return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value())); } Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); ActionStatus redeclareStatus = resourceInputsMergeBL.redeclareComponentInputsForInstance(origComponentInputs, updatedContainerComponent, newInstanceId); if (redeclareStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); + LOGGER.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); Either.right(redeclareStatus); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java new file mode 100644 index 0000000000..96f878abe0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java @@ -0,0 +1,416 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.aft.dme2.internal.google.common.annotations.VisibleForTesting; + +import fj.data.Either; + + +@org.springframework.stereotype.Component("ComponentInstanceRelashionMerge") +public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInterface { + private static Logger log = LoggerFactory.getLogger(ComponentInstanceRelationMerge.class); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + private MergeInstanceUtils mergeInstanceUtils; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + //All Relationships - container (service) holds info about all relations + //Filter by UniqueId in from/to + List<RequirementCapabilityRelDef> relationsFrom = getRelations(RequirementCapabilityRelDef::getFromNode, + containerComponent, + currentResourceInstance); + + List<RequirementCapabilityRelDef> relationsTo = getRelations(RequirementCapabilityRelDef::getToNode, + containerComponent, + currentResourceInstance); + + if (!relationsFrom.isEmpty() || !relationsTo.isEmpty()) { + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(currentResourceInstance, originComponent); + + if (vfcInstances != null) { + List<RelationMergeInfo> fromRelInfoList = convert(relationsFrom, rel -> mapRelationRequirement(rel, vfcInstances)); + List<RelationMergeInfo> toRelInfoList = convert(relationsTo, rel -> mapRelationCapability(rel, vfcInstances)); + + // Encapsulate all needed info in one container + VfRelationsMergeInfo vfRelationsMergeInfo = new VfRelationsMergeInfo(fromRelInfoList, toRelInfoList); + // Save it + dataHolder.setVfRelationsInfo(vfRelationsMergeInfo); + } + } + else { + log.debug("No relations relevant to currentResourceInstance {} found in container component", currentResourceInstance); + } + + } + + + @Override + public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Wrapper<Either<Component, ResponseFormat>> resultWrapper = new Wrapper<>(); + + VfRelationsMergeInfo vfRelationsMergeInfo = getRelationsMergeInfo(dataHolder, updatedContainerComponent, resultWrapper); + + ComponentInstance newComponentInstance = null; + if(resultWrapper.isEmpty()) { + //Component Instance + newComponentInstance = loadComponentInstance(updatedContainerComponent, newInstanceId, resultWrapper); + } + + if(resultWrapper.isEmpty() && vfRelationsMergeInfo != null) { + // Load VFCI and filter them by name + List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(newComponentInstance); + if(vfcInstances != null) { + Map<String, ComponentInstance> vfciMap = mergeInstanceUtils.convertToVfciNameMap(vfcInstances); + + // Process Relationships + List<RelationMergeInfo> toRelationsInfo = vfRelationsMergeInfo.getToRelationsInfo(); + Stream<RequirementCapabilityRelDef> toRelationsInfoStream = null; + if (toRelationsInfo != null) { + toRelationsInfoStream = toRelationsInfo.stream() + .map(oldCapInfo -> restoreCapabilityRelation(oldCapInfo, newInstanceId, vfciMap, updatedContainerComponent)) + .filter(Objects::nonNull); + } + + List<RelationMergeInfo> fromRelationsInfo = vfRelationsMergeInfo.getFromRelationsInfo(); + Stream<RequirementCapabilityRelDef> fromRelationsInfoStream = null; + if( fromRelationsInfo != null) { + //For Each old requirement relation info + fromRelationsInfoStream = fromRelationsInfo.stream() + .map(oldReqInfo -> restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent)) + .filter(Objects::nonNull); + } + + // Save relations in updated container (service) + List<RequirementCapabilityRelDef> updatedRelations = getUpdatedRelations(toRelationsInfoStream, fromRelationsInfoStream); + StorageOperationStatus saveResult = toscaOperationFacade.associateResourceInstances(updatedContainerComponent.getUniqueId(), updatedRelations); + if (saveResult == StorageOperationStatus.OK) { + resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); + } + else { + log.debug("Failed to associate instances of resource {} status is {}", updatedContainerComponent.getUniqueId(), saveResult); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(saveResult), updatedContainerComponent.getUniqueId()); + resultWrapper.setInnerElement(Either.right(responseFormat)); + } + } + } + + return resultWrapper.getInnerElement(); + } + + @VisibleForTesting + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + + @VisibleForTesting + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @VisibleForTesting + public void setMergeInstanceUtils(MergeInstanceUtils mergeInstanceUtils) { + this.mergeInstanceUtils = mergeInstanceUtils; + } + + /** + * @param containerComponent + * @param instanceId + * @param resultWrapper + * @return + */ + private ComponentInstance loadComponentInstance(Component containerComponent, String instanceId, + Wrapper<Either<Component, ResponseFormat>> resultWrapper) { + ComponentInstance componentInstance = containerComponent.getComponentInstanceById(instanceId).orElse(null); + if (componentInstance == null) { + log.debug("Failed to get VF instance by new VF instance ID: {}", instanceId); + resultWrapper.setInnerElement(Either.left(containerComponent)); + } + + return componentInstance; + } + + + private List<RequirementCapabilityRelDef> getUpdatedRelations(Stream<RequirementCapabilityRelDef> toRelationsInfoStream, + Stream<RequirementCapabilityRelDef> fromRelationsInfoStream) { + Stream<RequirementCapabilityRelDef> updatedRelationsStream = Stream.empty(); + + if (toRelationsInfoStream != null) { + updatedRelationsStream = Stream.concat(updatedRelationsStream, toRelationsInfoStream); + } + + if (fromRelationsInfoStream != null) { + updatedRelationsStream = Stream.concat(updatedRelationsStream, fromRelationsInfoStream); + } + + return updatedRelationsStream.collect(Collectors.toList()); + } + + private List<RequirementCapabilityRelDef> getRelations(Function<RequirementCapabilityRelDef, String> getNodeFunc, + Component containerComponent, + ComponentInstance currentResourceInstance) { + + final List<RequirementCapabilityRelDef> componentInstancesRelations = containerComponent.getComponentInstancesRelations(); + final String vfInstanceId = currentResourceInstance.getUniqueId(); + + return componentInstancesRelations.stream() + .filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId)) + .collect(Collectors.toList()); + } + + private List<RelationMergeInfo> convert(List<RequirementCapabilityRelDef> relationsDef, + Function<RequirementCapabilityRelDef, RelationMergeInfo> mapFunc) { + return relationsDef.stream() + .map(mapFunc::apply) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private RelationMergeInfo mapRelationCapability(RequirementCapabilityRelDef relDef, List<ComponentInstance> vfcInstances) { + // Id of the VfcInstance that is the owner of the capability + String ownerId = relDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId(); + return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceCapability(currVfcInst, relDef)); + } + + private RelationMergeInfo mapRelationRequirement(RequirementCapabilityRelDef relDef, List<ComponentInstance> vfcInstances) { + // Id of the VfcInstance that is the owner of the requirement + String ownerId = relDef.resolveSingleRelationship().getRelation().getRequirementOwnerId(); + return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relDef)); + } + + private RelationMergeInfo createRelationMergeInfo(List<ComponentInstance> vfcInstances, String ownerId, Function<ComponentInstance, RelationMergeInfo> mapFunc) { + return vfcInstances.stream() + .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) + .map(mapFunc::apply) + .filter(Objects::nonNull) + .findAny() + .orElse(null); + } + + + private RelationMergeInfo mapVfcInstanceCapability(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) { + String capabilityUniqueId = relDef.resolveSingleRelationship().getRelation().getCapabilityUid(); + + + String vfcInstanceName = vfcInstance.getName(); + String vfcUid = vfcInstance.getComponentUid(); + + Either<Resource, StorageOperationStatus> vfcResource = toscaOperationFacade.getToscaElement(vfcUid); + if(vfcResource.isLeft()) { + Resource vfc = vfcResource.left().value(); + + CapabilityDefinition capabilityDef = retrieveCapabilityDefinition(capabilityUniqueId, vfc); + String capabilityType; + String capabilityName; + if (capabilityDef != null) { + capabilityType = capabilityDef.getType(); + capabilityName = capabilityDef.getName(); + } + else { + log.debug("Failed to retrieve capability type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId); + capabilityType = null; + capabilityName = null; + } + + return new RelationMergeInfo(capabilityType, capabilityName, vfcInstanceName, relDef); + } + else { + log.debug("Failed to load VFC by uid {}", vfcUid); + return null; + } + } + + private RelationMergeInfo mapVfcInstanceRequirement(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) { + String requirementUniqueId = relDef.resolveSingleRelationship().getRelation().getRequirementUid(); + + String vfcInstanceName = vfcInstance.getName(); + String vfcUid = vfcInstance.getComponentUid(); + + Either<Resource, StorageOperationStatus> vfcResource = toscaOperationFacade.getToscaElement(vfcUid); + if(vfcResource.isLeft()) { + Resource vfc = vfcResource.left().value(); + + RequirementDefinition requirementDef = retrieveRequirementDefinition(requirementUniqueId, vfc); + String requirementType; + String requirementName; + if (requirementDef != null) { + requirementType = requirementDef.getCapability(); + requirementName = requirementDef.getName(); + } + else { + log.debug("Failed to retrieve requirement type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId); + requirementType = null; + requirementName = null; + } + + return new RelationMergeInfo(requirementType, requirementName, vfcInstanceName, relDef); + } + else { + log.debug("Failed to load VFC by uid {}", vfcUid); + return null; + } + } + + private CapabilityDefinition retrieveCapabilityDefinition(String uniqueId, Resource vfc) { + return vfc.getCapabilities().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())) + .findFirst() + .orElse(null); + } + + private String retrieveCapabilityUid(String name, Component vfc) { + return vfc.getCapabilities().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> name.equals(def.getName())) + .findFirst() + .map(CapabilityDefinition::getUniqueId) + .orElse(null); + } + + private RequirementDefinition retrieveRequirementDefinition(String uniqueId, Resource vfc) { + return vfc.getRequirements().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())) + .findFirst() + .orElse(null); + } + + private String retrieveRequirementUid(String name, Component vfc) { + return vfc.getRequirements().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> name.equals(def.getName())) + .findFirst() + .map(RequirementDefinition::getUniqueId) + .orElse(null); + } + + + + private VfRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder, + Component updatedContainerComponent, + Wrapper<Either<Component, ResponseFormat>> resultWrapper) { + VfRelationsMergeInfo vfRelationsMergeInfo = dataHolder.getVfRelationsMergeInfo(); + if (vfRelationsMergeInfo == null) { + log.debug("There is no info about relations should be restored."); + resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); + } + + return vfRelationsMergeInfo; + } + + + private RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo, + String newInstanceId, + Map<String, ComponentInstance> vfciMap, + Component updatedContainerComponent) { + String oldVfcInstanceName = oldCapInfo.getVfcInstanceName(); + + ComponentInstance newVfcInstance = vfciMap.get(oldVfcInstanceName); + if (newVfcInstance != null) { + // Append relation to updated container + RequirementCapabilityRelDef oldRelDef = oldCapInfo.getRelDef(); + oldRelDef.setToNode(newInstanceId); + + RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation(); + oldRelationshipInfo.setCapabilityOwnerId(newVfcInstance.getUniqueId()); + oldRelationshipInfo.getRelationship().setType(oldCapInfo.getCapReqType()); + + + String vfcUid = newVfcInstance.getComponentUid(); + Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(vfcUid); + + if(eitherComponent.isLeft()) { + String capabilityUid = retrieveCapabilityUid(oldCapInfo.getCapReqName() , eitherComponent.left().value()); + oldRelationshipInfo.setCapabilityUid(capabilityUid); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid); + } + + updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef); + return oldRelDef; + } + else { + log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName); + return null; + } + } + + + + private RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo, + String newInstanceId, + Map<String, ComponentInstance> vfciMap, + Component updatedContainerComponent) { + String oldVfcInstanceName = oldReqInfo.getVfcInstanceName(); + + ComponentInstance newVfcInstance = vfciMap.get(oldReqInfo.getVfcInstanceName()); + if (newVfcInstance != null) { + // Append relation to updated container + RequirementCapabilityRelDef oldRelDef = oldReqInfo.getRelDef(); + oldRelDef.setFromNode(newInstanceId); + + RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation(); + oldRelationshipInfo.setRequirementOwnerId(newVfcInstance.getUniqueId()); + oldRelationshipInfo.getRelationship().setType(oldReqInfo.getCapReqType()); + + String vfcUid = newVfcInstance.getComponentUid(); + Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(vfcUid); + + if(eitherComponent.isLeft()) { + String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName() , eitherComponent.left().value()); + oldRelationshipInfo.setRequirementUid(requirementUid); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid); + } + + updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef); + return oldRelDef; + } + else { + log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName); + return null; + } + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java new file mode 100644 index 0000000000..5dcb1dda79 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; + +public interface ComponentsMergeCommand { + + /** + * encapsulates the logic of merging component inner entities from the previous component into the currently updated component + * @param prevComponent the old component, whose entities need to be merged + * @param currentComponent the new component, whose entities need to be merged + * @return the status of the merge process + */ + ActionStatus mergeComponents(Component prevComponent, Component currentComponent); + + /** + * + * @return short description of the command for logging purposes + */ + String description(); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java index c5fb1d4a86..ac0959897d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java @@ -6,8 +6,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; @@ -23,6 +24,10 @@ public class DataForMergeHolder { private Map<String, ArtifactDefinition> origCompInstDeploymentArtifactsCreatedOnTheInstance; private Map<String, ArtifactDefinition> origCompInstInformationalArtifactsCreatedOnTheInstance; private List<ArtifactDefinition> origComponentInstanceHeatEnvArtifacts; + private VfRelationsMergeInfo vfRelationsMergeInfo; + private List<CapabilityDefinition> origInstanceCapabilities; + private Component origInstanceNode; + private String origComponentInstId; public DataForMergeHolder() { origComponentInstanceInputs = new ArrayList<>(); @@ -30,7 +35,7 @@ public class DataForMergeHolder { origComponentInputs = new ArrayList<>(); origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); - + origInstanceCapabilities = new ArrayList<>(); } public List<ArtifactDefinition> getOrigComponentInstanceHeatEnvArtifacts() { @@ -109,6 +114,35 @@ public class DataForMergeHolder { origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts; } + public void setVfRelationsInfo(VfRelationsMergeInfo vfRelationsMergeInfo) { + this.vfRelationsMergeInfo = vfRelationsMergeInfo; + } + + public VfRelationsMergeInfo getVfRelationsMergeInfo() { + return vfRelationsMergeInfo; + } + + public List<CapabilityDefinition> getOrigInstanceCapabilities() { + return origInstanceCapabilities; + } + public void setOrigInstanceCapabilities(List<CapabilityDefinition> origInstanceCapabilities) { + this.origInstanceCapabilities = origInstanceCapabilities; + } + public Component getOrigInstanceNode() { + return origInstanceNode; + } + + public void setOrigInstanceNode(Component origInstanceNode) { + this.origInstanceNode = origInstanceNode; + } + + public String getOrigComponentInstId() { + return origComponentInstId; + } + + public void setOrigComponentInstId(String origComponentInstId) { + this.origComponentInstId = origComponentInstId; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java new file mode 100644 index 0000000000..4ab802ad35 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java @@ -0,0 +1,49 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; + +public class RelationMergeInfo { + private String capReqType; + private String vfcInstanceName; + private RequirementCapabilityRelDef relDef; + private String capReqName; + + public RelationMergeInfo(String capReqType, String capReqName, String vfcInstanceName, RequirementCapabilityRelDef relDef) { + this.capReqType = capReqType; + this.capReqName = capReqName; + this.vfcInstanceName = vfcInstanceName; + this.relDef = relDef; + } + + public String getCapReqType() { + return capReqType; + } + + public void setCapReqType(String type) { + this.capReqType = type; + } + + public String getVfcInstanceName() { + return vfcInstanceName; + } + + public void setVfcInstanceName(String vfcInstanceName) { + this.vfcInstanceName = vfcInstanceName; + } + + public RequirementCapabilityRelDef getRelDef() { + return relDef; + } + + public void setRelDef(RequirementCapabilityRelDef relDef) { + this.relDef = relDef; + } + + public String getCapReqName() { + return capReqName; + } + + public void setCapReqName(String capReqName) { + this.capReqName = capReqName; + } +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java new file mode 100644 index 0000000000..e116b66408 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; + +public class VfRelationsMergeInfo { + private List<RelationMergeInfo> fromRelationsInfo; + private List<RelationMergeInfo> toRelationsInfo; + + public VfRelationsMergeInfo(List<RelationMergeInfo> fromRelationsInfo, List<RelationMergeInfo> toRelationsInfo) { + this.fromRelationsInfo = fromRelationsInfo; + this.toRelationsInfo = toRelationsInfo; + } + + public List<RelationMergeInfo> getFromRelationsInfo() { + return fromRelationsInfo; + } + + public void setFromRelationsInfo(List<RelationMergeInfo> fromRelationsInfo) { + this.fromRelationsInfo = fromRelationsInfo; + } + + public List<RelationMergeInfo> getToRelationsInfo() { + return toRelationsInfo; + } + + public void setToRelationsInfo(List<RelationMergeInfo> toRelationsInfo) { + this.toRelationsInfo = toRelationsInfo; + } + +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java index 96d3bce97e..139ac386a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java @@ -1,11 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.List; - import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.springframework.stereotype.Component; +import java.util.Collections; +import java.util.List; + @Component public class DataDefinitionsValuesMergingBusinessLogic { @@ -30,6 +31,11 @@ public class DataDefinitionsValuesMergingBusinessLogic { } + public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition, List<T> updatedInstanceDataDefinition) { + List<InputDefinition> emptyInputsList = Collections.emptyList(); + mergeInstanceDataDefinitions(oldInstanceDataDefinition, emptyInputsList, updatedInstanceDataDefinition, emptyInputsList); + } + private void mergeInstanceDefinition(MergePropertyData mergeData) { if (isSameType(mergeData.getOldProp(), mergeData.getNewProp())) { propertyValueMergeBL.mergePropertyValue(mergeData.getOldProp(), mergeData.getNewProp(), mergeData.getGetInputNamesToMerge()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java index 63a7a1b3a0..df65c1161f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.components.merge.property; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + import java.util.ArrayList; import java.util.List; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - /** * A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link org.openecomp.sdc.be.model.ComponentInstanceInput}) * that its value needs to be merged during an upgrade of a VSP. diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java index 6b083596c7..318840d60a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java @@ -1,15 +1,7 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - -import org.openecomp.sdc.be.components.impl.ImportUtils; +import com.google.gson.Gson; +import fj.data.Either; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -22,9 +14,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.gson.Gson; - -import fj.data.Either; +import javax.annotation.Resource; +import java.util.*; +import java.util.stream.Collectors; @Component public class PropertyDataValueMergeBusinessLogic { @@ -88,39 +80,6 @@ public class PropertyDataValueMergeBusinessLogic { return propertyConvertor.convertToToscaObject(propertyType, propValue, innerType, dataTypes); } - - @SuppressWarnings("unchecked") - private Object removeUnwantedGetInputValues(Object val, List<String> getInputNamesToMerge) { - if (val instanceof Map) { - return removeUnwantedGetInputValues((Map<String, Object>) val, getInputNamesToMerge); - } - if (val instanceof List) { - return removeUnwantedGetInputValues((List<Object>)val, getInputNamesToMerge); - } - return val; - } - - private List<Object> removeUnwantedGetInputValues(List<Object> listVal, List<String> getInputNamesToMerge) { - return listVal.stream().map(val -> removeUnwantedGetInputValues(val, getInputNamesToMerge)).collect(Collectors.toList()); - } - - private Map<String, Object> removeUnwantedGetInputValues(Map<String, Object> val, List<String> getInputNamesToMerge) { - return val.entrySet().stream().filter(entry -> !isGetInputEntry(entry) || isGetInputToMerge(getInputNamesToMerge, entry)) - .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), getInputNamesToMerge))); - } - - private boolean isGetInputToMerge(List<String> getInputNamesToMerge, Map.Entry<String, Object> entry) { - return getInputNamesToMerge.contains(retrieveGetInputInputName(entry.getValue())); - } - - private String retrieveGetInputInputName(Object getInputValue) { - return getInputValue instanceof List ? (String)((List) getInputValue).get(0) : (String)getInputValue; - } - - private boolean isGetInputEntry(Map.Entry<String, Object> oldValEntry) { - return oldValEntry.getKey().equals(ImportUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - private boolean isEmptyValue(Object val) { return val == null || val instanceof Map && ((Map) val).isEmpty() || diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java index 09f26a39ee..df3030567d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + public class PropertyInstanceMergeDataBuilder { private final static PropertyInstanceMergeDataBuilder INSTANCE = new PropertyInstanceMergeDataBuilder(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java index 88601bb521..9fcb864fe9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be.components.merge.property; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; + import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.apache.commons.lang.StringUtils; -import org.openecomp.sdc.be.components.impl.ImportUtils; - public abstract class PropertyValueMerger { abstract Object merge(Object oldVal, Object newVal, List<String> someStrings); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java index 39381e7322..ce0ed0eed2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.List; - import org.springframework.stereotype.Component; +import java.util.List; + @Component("scalar-prop-value-merger") public class ScalarPropertyValueMerger extends PropertyValueMerger { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java index 9d11eb9aaf..cdfeded356 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java @@ -1,14 +1,13 @@ package org.openecomp.sdc.be.components.merge.resource; +import fj.data.Either; import org.openecomp.sdc.be.components.merge.GlobalTypesMergeBusinessLogic; import org.openecomp.sdc.be.components.merge.TopologyComparator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component public class MergeResourceBLFactory { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java index 251fb1a64e..0ffe693187 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java @@ -1,62 +1,38 @@ package org.openecomp.sdc.be.components.merge.resource; -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic { - private final static Logger log = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class); - @javax.annotation.Resource - private ComponentInputsMergeBL inputsValuesMergeBL; + private List<ComponentsMergeCommand> componentMergingCommands; - @javax.annotation.Resource - private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBL; - - @javax.annotation.Resource - private ComponentInstanceInputsMergeBL instanceInputsValueMergeBL; + public ResourceDataMergeBusinessLogic(List<ComponentsMergeCommand> componentMergingCommands) { + this.componentMergingCommands = componentMergingCommands; + } @Override public ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { if (oldResource == null) { return ActionStatus.OK; } - - ActionStatus mergeInstInputsStatus = instancePropertiesValueMergeBL.mergeComponentInstancesProperties(oldResource, newResource); - if (mergeInstInputsStatus != ActionStatus.OK) { - log.error("failed to merge instance properties of resource {} status is {}", newResource.getUniqueId(), mergeInstInputsStatus); - return mergeInstInputsStatus; - } - - ActionStatus mergeInstPropsStatus = instanceInputsValueMergeBL.mergeComponentInstancesInputs(oldResource, newResource); - if (mergeInstPropsStatus != ActionStatus.OK) { - log.error("failed to merge instance inputs of resource {} status is {}", newResource.getUniqueId(), mergeInstPropsStatus); - return mergeInstPropsStatus; - } - - ActionStatus mergeInputsStatus = mergeInputs(oldResource, newResource); - if (mergeInputsStatus != ActionStatus.OK) { - log.error("failed to merge inputs of resource {} status is {}", newResource.getUniqueId(), mergeInputsStatus); - return mergeInputsStatus; + for (ComponentsMergeCommand componentMergeCommand : componentMergingCommands) { + ActionStatus mergeStatus = componentMergeCommand.mergeComponents(oldResource, newResource); + if (mergeStatus != ActionStatus.OK) { + LOGGER.error("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), mergeStatus); + return mergeStatus; + } } return ActionStatus.OK; } - private ActionStatus mergeInputs(Resource oldResource, Resource newResource) { - List<InputDefinition> inputsToMerge = newResource.getInputs() != null ? newResource.getInputs() : new ArrayList<>(); - return inputsValuesMergeBL.mergeAndRedeclareComponentInputs(oldResource, newResource, inputsToMerge); - } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java new file mode 100644 index 0000000000..4ff7e06db5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java @@ -0,0 +1,257 @@ +package org.openecomp.sdc.be.components.merge.utils; + +import fj.data.Either; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.annotations.VisibleForTesting; +import java.util.*; +import java.util.stream.Collectors; + +import static java.util.function.Function.identity; + +/** + * This class is Utils class but it should be bean + * @author dr2032 + * + */ +@org.springframework.stereotype.Component("MergeInstanceUtils") +public class MergeInstanceUtils { + private Logger log = LoggerFactory.getLogger(MergeInstanceUtils.class); + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + /** + * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance + * @param container containing new component instance + * @param origInstanceNode old component (in case of PROXY it should be actual service) + * @param newInstanceId - ID of new instance of the component + * @param oldCapabilitiesOwnerIds + * @return + */ + public Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, + Component origInstanceNode, + String newInstanceId, + List<String> oldCapabilitiesOwnerIds) { + + Map<String, String> resultMap; + + if (ModelConverter.isAtomicComponent(origInstanceNode) || isCVFC(origInstanceNode)) { + resultMap = prepareMapForAtomicComponent(newInstanceId, oldCapabilitiesOwnerIds); + } + else { + resultMap = prepareMapForNonAtomicComponent(container, origInstanceNode, newInstanceId, oldCapabilitiesOwnerIds); + } + + return resultMap; + } + + + private static boolean isCVFC(Component component) { + ComponentTypeEnum componentType = component.getComponentType(); + if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { + return false; + } + + Resource resource = (Resource) component; + ResourceTypeEnum resourceType = resource.getResourceType(); + return resourceType == ResourceTypeEnum.CVFC; + } + + + /** + * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance + * @param oldInstance + * @param newInstance + * @return + */ + public Map<String, String> mapOldToNewCapabilitiesOwnerIds(ComponentInstance oldInstance, ComponentInstance newInstance) { + List<ComponentInstance> oldVfcInstances = getVfcInstances(oldInstance); + List<ComponentInstance> newVfcInstances = getVfcInstances(newInstance); + + Map<String, ComponentInstance> newVfciNameMap = convertToVfciNameMap(newVfcInstances); + + return oldVfcInstances.stream() + .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName())) + .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId())); + } + + + /** + * Method converts list of Component Instances to map of the instances where the key is their name + * @param componentInstances + * @return + */ + public Map<String, ComponentInstance> convertToVfciNameMap(List<ComponentInstance> componentInstances) { + return componentInstances != null ? + componentInstances.stream() + .collect(Collectors.toMap(ComponentInstance::getName, identity())): Collections.emptyMap(); + } + + + + /** + * Returns List of componentInstances by specified componentInstance + * If componentInstance is for atomic component the returned list will contain the specified componentInstance only. + * @param componentInstance + * @return + */ + public List<ComponentInstance> getVfcInstances(ComponentInstance componentInstance) { + if (componentInstance == null) { + return Collections.emptyList(); + } + + + List<ComponentInstance> vfcInstances; + + String componentId = componentInstance.getActualComponentUid(); + Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(componentId); + + if(eitherComponent.isLeft()) { + Component component = eitherComponent.left().value(); + vfcInstances = getVfcInstances(componentInstance, component); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", componentId); + vfcInstances = Collections.emptyList(); + } + + return vfcInstances; + } + + + /** + * Returns List of componentInstances by specified componentInstance and component + * If componentInstance is for atomic component the returned list will contain the specified componentInstance only. + * @param componentInstance + * @param eitherComponent + * @return + */ + public List<ComponentInstance> getVfcInstances(ComponentInstance componentInstance, Component component) { + if (componentInstance == null || component == null) { + return Collections.emptyList(); + } + + + List<ComponentInstance> vfcInstances; + + if (ModelConverter.isAtomicComponent(component) || isCVFC(component)) { + if (componentInstance.getIsProxy()) { + // Component is proxy and it doesn't contain required data + vfcInstances = getVfcInstances(componentInstance); + } + else { + vfcInstances = Arrays.asList(componentInstance); + } + } + else { + vfcInstances = recursiveScanForAtomicComponentInstances(component); + } + + return vfcInstances; + } + + + @VisibleForTesting + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + + + /** + * @param component + * @return + */ + private List<ComponentInstance> recursiveScanForAtomicComponentInstances(Component component) { + List<ComponentInstance> vfcInstances; + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + // Go recursively to collect atomic components only + vfcInstances = componentInstances.stream() + .map(this::getVfcInstances) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + else { + vfcInstances = Collections.emptyList(); + } + + return vfcInstances; + } + + + + /** + * @param newInstanceId + * @param oldCapabilitiesOwnerIds + * @return + */ + private Map<String, String> prepareMapForAtomicComponent(String newInstanceId, List<String> oldCapabilitiesOwnerIds) { + Map<String, String> resultMap; + + int oldCapabilityOwnerIdsSize = oldCapabilitiesOwnerIds.size(); + if (oldCapabilityOwnerIdsSize == 1) { + resultMap = new HashMap<>(); + resultMap.put(oldCapabilitiesOwnerIds.get(0), newInstanceId); + } + else { + log.debug("For automic component the list of old capabilities owner Ids should contains one element while actual size is {},", oldCapabilityOwnerIdsSize); + resultMap = Collections.emptyMap(); + } + + return resultMap; + } + + /** + * @param container + * @param origInstanceNode + * @param newInstanceId + * @param oldCapabilitiesOwnerIds + * @return + */ + private Map<String, String> prepareMapForNonAtomicComponent(Component container, Component origInstanceNode, + String newInstanceId, List<String> oldCapabilitiesOwnerIds) { + Map<String, String> resultMap; + List<ComponentInstance> oldVfcInstances = recursiveScanForAtomicComponentInstances(origInstanceNode); + + ComponentInstance newInstance = container.getComponentInstanceById(newInstanceId).orElse(null); + if (newInstance == null) { + log.debug("Failed to get component instance by newInstanceId: {}.", newInstanceId); + resultMap = Collections.emptyMap(); + } + else { + resultMap = mapOldVfcIdsToNewOnes(oldCapabilitiesOwnerIds, oldVfcInstances, newInstance); + } + return resultMap; + } + + /** + * @param oldCapabilitiesOwnerIds + * @param oldVfcInstances + * @param newInstance + * @return + */ + private Map<String, String> mapOldVfcIdsToNewOnes(List<String> oldCapabilitiesOwnerIds, + List<ComponentInstance> oldVfcInstances, ComponentInstance newInstance) { + List<ComponentInstance> newVfcInstances = getVfcInstances(newInstance); + Map<String, ComponentInstance> newVfciNameMap = convertToVfciNameMap(newVfcInstances); + + return oldVfcInstances.stream() + .filter(oldVfc -> oldCapabilitiesOwnerIds.contains(oldVfc.getUniqueId())) + .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName())) + .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId())); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java new file mode 100644 index 0000000000..469ae31f2d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java @@ -0,0 +1,173 @@ +package org.openecomp.sdc.be.components.path; + +import fj.data.Either; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +@Component("forwardingPathValidator") +public class ForwardingPathValidator { + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + private static final Logger LOGGER = LoggerFactory.getLogger(ForwardingPathValidator.class); + private static final int PATH_NAME_LENGTH = 200; + private static final int PROTOCOL_LENGTH = 200; + private static final int DESTINATION_PORT_LENGTH = 200; + + public Either<Boolean, ResponseFormat> validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths, + String serviceId, boolean isUpdate) { + for (ForwardingPathDataDefinition path : paths) { + Either<Boolean, ResponseFormat> forwardingPathResponseEither = validateForwardingPath(path, + serviceId, isUpdate); + if (forwardingPathResponseEither.isRight()) { + return forwardingPathResponseEither; + } + } + return Either.left(Boolean.TRUE); + } + + private Either<Boolean, ResponseFormat> validateForwardingPath(ForwardingPathDataDefinition path, + String serviceId, boolean isUpdate) { + ResponseFormatManager responseFormatManager = getResponseFormatManager(); + + Either<Boolean, ResponseFormat> errorResponseName = validateName(path, + responseFormatManager, serviceId, isUpdate); + if (errorResponseName != null) + return errorResponseName; + + Either<Boolean, ResponseFormat> protocolErrorResponse = validateProtocol(path, responseFormatManager); + if (protocolErrorResponse != null) + return protocolErrorResponse; + + Either<Boolean, ResponseFormat> portNumberResponse = validateDestinationPortNumber(path, responseFormatManager); + if (portNumberResponse != null) + return portNumberResponse; + + return Either.left(true); + } + + private Either<Boolean, ResponseFormat> validateDestinationPortNumber(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager) { + if (dataDefinition.getDestinationPortNumber() != null && + dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH ) { + LOGGER.debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ", + dataDefinition.getDestinationPortNumber()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, dataDefinition.getDestinationPortNumber()); + return Either.right(errorResponse); + } + return null; + } + + private Either<Boolean, ResponseFormat> validateProtocol(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager) { + if (dataDefinition.getProtocol() != null && dataDefinition.getProtocol().length() > PROTOCOL_LENGTH) { + LOGGER.debug("Forwarding path protocol {} too long, , maximum allowed 200 characters ", dataDefinition.getProtocol()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH, dataDefinition.getProtocol()); + return Either.right(errorResponse); + } + return null; + } + + private Either<Boolean, ResponseFormat> validateName(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager, + String serviceId, boolean isUpdate) { + String pathName = dataDefinition.getName(); + Either<Boolean, ResponseFormat> pathEmptyResponse = validatePathNameIfEmpty(responseFormatManager, pathName); + if (pathEmptyResponse != null) + return pathEmptyResponse; + + Either<Boolean, ResponseFormat> pathLengthResponse = validatePathNameLength(responseFormatManager, pathName); + if (pathLengthResponse != null) + return pathLengthResponse; + + Either<Boolean, ResponseFormat> isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager ); + if(isPathNameUniqueResponse.isRight()) { + return Either.right(isPathNameUniqueResponse.right().value()); + } + if (!isPathNameUniqueResponse.left().value()) { + LOGGER.debug("Forwarding path name {} already in use ", dataDefinition.getName()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_NAME_ALREADY_IN_USE, dataDefinition.getName()); + return Either.right(errorResponse); + } + return null; + } + + private Either<Boolean, ResponseFormat> validatePathNameLength(ResponseFormatManager responseFormatManager, String pathName) { + if (pathName.length() > PATH_NAME_LENGTH) { + LOGGER.debug("Forwarding path name {} too long, , maximum allowed 200 characters ", pathName); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_NAME_MAXIMUM_LENGTH, pathName); + return Either.right(errorResponse); + } + return null; + } + + private Either<Boolean, ResponseFormat> validatePathNameIfEmpty(ResponseFormatManager responseFormatManager, String pathName) { + if (StringUtils.isEmpty(pathName)) { + LOGGER.debug("Forwarding Path Name can't be empty"); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.FORWARDING_PATH_NAME_EMPTY); + return Either.right(errorResponse); + } + return null; + } + + + private Either<Boolean, ResponseFormat> validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId, + boolean isUpdate, ResponseFormatManager responseFormatManager) { + boolean isPathNameUnique = false; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreForwardingPath(false); + Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade + .getToscaElement(serviceId, filter); + if (forwardingPathOrigin.isRight()){ + return Either.right(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values(); + Map<String, String> pathNames = new HashMap<>(); + allPaths.forEach( path -> pathNames.put(path.getUniqueId(), path.getName()) ); + + if (isUpdate){ + for(Map.Entry<String, String> entry : pathNames.entrySet()){ + if (entry.getKey().equals(dataDefinition.getUniqueId()) && entry.getValue(). + equals(dataDefinition.getName())) { + isPathNameUnique = true; + } + + if(entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())){ + isPathNameUnique = true; + } + } + } + else + if (!pathNames.values().contains(dataDefinition.getName())){ + isPathNameUnique = true; + } + + return Either.left(isPathNameUnique); + } + + protected ResponseFormatManager getResponseFormatManager() { + return ResponseFormatManager.getInstance(); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java new file mode 100644 index 0000000000..f59831621c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component +public class ComponentInstanceInputPropertyDecelerator extends DefaultPropertyDecelerator<ComponentInstance, ComponentInstanceInput> { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceInputPropertyDecelerator.class); + private ToscaOperationFacade toscaOperationFacade; + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + public ComponentInstanceInputPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; + } + + @Override + ComponentInstanceInput createDeclaredProperty(PropertyDataDefinition prop) { + return new ComponentInstanceInput(prop); + } + + @Override + Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceInput> properties) { + log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + Map<String, List<ComponentInstanceInput>> instProperties = Collections.singletonMap(cmptInstanceId, properties); + return toscaOperationFacade.addComponentInstanceInputsToComponent(component, instProperties); + } + + @Override + Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { + log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); + return component.getComponentInstanceById(propertiesOwnerId); + } + + @Override + void addPropertiesListToInput(ComponentInstanceInput declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List<ComponentInstanceInput> inputsValueList = input.getInputs(); + if(inputsValueList == null) { + inputsValueList = new ArrayList<>(); // adding the property with the new value for UI + } + inputsValueList.add(declaredProp); + input.setInputs(inputsValueList); + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId()); + if (CollectionUtils.isEmpty(componentInstanceInputsByInputId)) { + return StorageOperationStatus.OK; + } + componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); + return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java new file mode 100644 index 0000000000..ab4c4e29c2 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component +public class ComponentInstancePropertyDecelerator extends DefaultPropertyDecelerator<ComponentInstance, ComponentInstanceProperty> { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstancePropertyDecelerator.class); + private ToscaOperationFacade toscaOperationFacade; + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + public ComponentInstancePropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; + } + + @Override + ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) { + return new ComponentInstanceProperty(prop); + } + + @Override + Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceProperty> properties) { + log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + Map<String, List<ComponentInstanceProperty>> instProperties = Collections.singletonMap(cmptInstanceId, properties); + return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties, cmptInstanceId); + } + + @Override + Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { + log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); + return component.getComponentInstanceById(propertiesOwnerId); + } + + @Override + void addPropertiesListToInput(ComponentInstanceProperty declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List<ComponentInstanceProperty> propertiesList = input.getProperties(); + if(propertiesList == null) { + propertiesList = new ArrayList<>(); // adding the property with the new value for UI + } + propertiesList.add(declaredProp); + input.setProperties(propertiesList); + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + List<ComponentInstanceProperty> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, input.getUniqueId()); + if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) { + return StorageOperationStatus.OK; + } + componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath())); + return toscaOperationFacade.updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), componentInstancePropertiesDeclaredAsInput); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java new file mode 100644 index 0000000000..e053096480 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java @@ -0,0 +1,413 @@ +package org.openecomp.sdc.be.components.property; + +import com.google.gson.Gson; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; + +public abstract class DefaultPropertyDecelerator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements PropertyDecelerator { + + private static final Logger log = LoggerFactory.getLogger(DefaultPropertyDecelerator.class); + private static final short LOOP_PROTECTION_LEVEL = 10; + private final Gson gson = new Gson(); + private ComponentsUtils componentsUtils; + private PropertyOperation propertyOperation; + + public DefaultPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) { + this.componentsUtils = componentsUtils; + this.propertyOperation = propertyOperation; + } + + @Override + public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare) { + log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + return resolvePropertiesOwner(component, propertiesOwnerId) + .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare)) + .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); + } + + abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop); + + abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PROPERTYTYPE> properties); + + abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId); + + abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, PropertyDataDefinition originalProp, InputDefinition input); + + private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) { + log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId); + return StorageOperationStatus.NOT_FOUND; + } + + private Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, PropertiesOwner propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) { + PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component.getUniqueId(), propertiesOwner, propsToDeclare); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()) + .left() + .map(updatePropsRes -> inputsProperties.getInputsToCreate()); + } + + private PropertiesDeclarationData createInputsAndOverridePropertiesValues(String componentId, PropertiesOwner propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) { + List<PROPERTYTYPE> declaredProperties = new ArrayList<>(); + List<InputDefinition> createdInputs = propsToDeclare.stream() + .map(propInput -> declarePropertyInput(componentId, propertiesOwner, declaredProperties, propInput)) + .collect(Collectors.toList()); + return new PropertiesDeclarationData(createdInputs, declaredProperties); + } + + private InputDefinition declarePropertyInput(String componentId, PropertiesOwner propertiesOwner, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) { + PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput); + propInput.setOwnerId(null); + propInput.setParentUniqueId(null); + InputDefinition inputDefinition = createInput(componentId, propertiesOwner, propInput, prop); + PROPERTYTYPE declaredProperty = createDeclaredProperty(prop); + if(!declaredProperties.contains(declaredProperty)){ + declaredProperties.add(declaredProperty); + } + addPropertiesListToInput(declaredProperty, prop, inputDefinition); + return inputDefinition; + } + + private InputDefinition createInput(String componentId, PropertiesOwner propertiesOwner, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + String generatedInputName = generateInputName(propertiesOwner.getNormalizedName(), propInput); + return createInputFromProperty(componentId, propertiesOwner, generatedInputName, propInput, prop); + } + + private String generateInputName(String inputName, ComponentInstancePropInput propInput) { + String[] parsedPropNames = propInput.getParsedPropNames(); + if(parsedPropNames != null){ + for(String str: parsedPropNames){ + inputName += "_" + str; + } + } else { + inputName += "_" + propInput.getName(); + } + return inputName; + } + + private PropertyDataDefinition resolveProperty(List<PROPERTYTYPE> propertiesToCreate, ComponentInstancePropInput propInput) { + Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream() + .filter(p -> p.getName().equals(propInput.getName())) + .findFirst(); + return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput; + } + + private InputDefinition createInputFromProperty(String componentId, PropertiesOwner propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + String propertiesName = propInput.getPropertiesName() ; + PropertyDefinition selectedProp = propInput.getInput(); + String[] parsedPropNames = propInput.getParsedPropNames(); + InputDefinition input; + boolean complexProperty = false; + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + complexProperty = true; + input = new InputDefinition(selectedProp); + }else{ + input = new InputDefinition(prop); + } + input.setDefaultValue(prop.getValue()); + input.setName(inputName); + input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName())); + input.setInputPath(propertiesName); + input.setInstanceUniqueId(propertiesOwner.getUniqueId()); + input.setPropertyId(propInput.getUniqueId()); + changePropertyValueToGetInputValue(inputName, parsedPropNames, input, prop, complexProperty); + ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(propertiesOwner.getUniqueId()); + ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(propertiesOwner.getName()); + return input; + } + + private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop, boolean complexProperty) { + JSONObject jobject = new JSONObject(); + if(prop.getValue() == null || prop.getValue().isEmpty()){ + if(complexProperty){ + + jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); + prop.setValue(jobject.toJSONString()); + + }else{ + + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + } + + }else{ + + String value = prop.getValue(); + Object objValue = new Yaml().load(value); + if( objValue instanceof Map || objValue instanceof List){ + if(!complexProperty){ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + + }else{ + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue; + createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); + + String json = gson.toJson(mappedToscaTemplate); + prop.setValue(json); + + } + + }else{ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + } + + } + + + if(CollectionUtils.isEmpty(prop.getGetInputValues())){ + prop.setGetInputValues(new ArrayList<>()); + } + List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues(); + + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputId(input.getUniqueId()); + getInputValueDataDefinition.setInputName(input.getName()); + getInputValues.add(getInputValueDataDefinition); + } + + private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ + + while(i >= 1){ + if( i == parsedPropNames.length -1){ + JSONObject jobProp = new JSONObject(); + jobProp.put(GET_INPUT, inputName); + ooj.put(parsedPropNames[i], jobProp); + i--; + return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); + }else{ + JSONObject res = new JSONObject(); + res.put(parsedPropNames[i], ooj); + i --; + res = createJSONValueForProperty (i, parsedPropNames, res, inputName); + return res; + } + } + + return ooj; + } + + private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){ + while(index < inputNames.length){ + if(lhm1.containsKey(inputNames[index])){ + Object value = lhm1.get(inputNames[index]); + if (value instanceof Map){ + if(index == inputNames.length -1){ + ((Map) value).put(GET_INPUT, inputName); + return (Map) value; + + }else{ + index++; + return createInputValue((Map)value, index, inputNames, inputName); + } + }else{ + Map<String, Object> jobProp = new HashMap<>(); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + lhm1.put(inputNames[index], jobProp); + return lhm1; + }else{ + lhm1.put(inputNames[index], jobProp); + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + }else{ + Map<String, Object> jobProp = new HashMap<>(); + lhm1.put(inputNames[index], jobProp); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + return jobProp; + }else{ + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + } + return lhm1; + } + + private class PropertiesDeclarationData { + private List<InputDefinition> inputsToCreate; + private List<PROPERTYTYPE> propertiesToUpdate; + + PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PROPERTYTYPE> propertiesToUpdate) { + this.inputsToCreate = inputsToCreate; + this.propertiesToUpdate = propertiesToUpdate; + } + + List<InputDefinition> getInputsToCreate() { + return inputsToCreate; + } + + List<PROPERTYTYPE> getPropertiesToUpdate() { + return propertiesToUpdate; + } + } + + Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List<String> pathOfComponentInstances) { + Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete); + String value = inputValue.getValue(); + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value); + + resetInputName(mappedToscaTemplate, inputForDelete.getName()); + + value = ""; + if(!mappedToscaTemplate.isEmpty()){ + Either result = cleanNestedMap(mappedToscaTemplate , true); + Map modifiedMappedToscaTemplate = mappedToscaTemplate; + if (result.isLeft()) + modifiedMappedToscaTemplate = (Map)result.left().value(); + else + log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation + value = gson.toJson(modifiedMappedToscaTemplate); + } + inputValue.setValue(value); + + + List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues(); + if(getInputsValues != null && !getInputsValues.isEmpty()){ + Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny(); + if(op.isPresent()){ + getInputsValues.remove(op.get()); + } + } + inputValue.setGetInputValues(getInputsValues); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue()); + if (findDefaultValue.isRight()) { + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); + return deleteEither; + + } + String defaultValue = findDefaultValue.left().value(); + inputValue.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + return deleteEither; + } + + private void resetInputName(Map<String, Object> lhm1, String inputName){ + for (Map.Entry<String, Object> entry : lhm1.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { + value = ""; + lhm1.remove(key); + } else if (value instanceof Map) { + Map<String, Object> subMap = (Map<String, Object>)value; + resetInputName(subMap, inputName); + } else { + continue; + } + + } + } + + private Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){ + if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){ + if (deepClone){ + if (!(mappedToscaTemplate instanceof HashMap)) + return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() ); + else + mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone(); + } + return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , LOOP_PROTECTION_LEVEL ) ); + } + else { + log.debug("mappedToscaTemplate is empty "); + return Either.right("mappedToscaTemplate is empty "); + } + } + + /* Mutates the object + * Tail recurse -> traverse the tosca elements and remove nested empty map properties + * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected + * + * @param toscaElement - expected map of tosca values + * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map. + **/ + private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){ + //region - Stop if map is empty + if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map)) + return toscaElement; + //endregion + //region - Remove empty map entries & return null iff empty map + if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) { + Object ret; + Set<Object> keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException + for( Object key : ((Map)toscaElement).keySet() ) { + Object value = ((Map) toscaElement).get(key); + ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel ); + if ( ret == null ) + keysToRemove.add(key); + } + Collection set = ((Map) toscaElement).keySet(); + if (CollectionUtils.isNotEmpty(set)) + set.removeAll(keysToRemove); + + if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check + return null; + } + //endregion + else + return null; + return toscaElement; + } + + //@returns true iff map nested maps are all empty + //ignores other collection objects + private boolean isEmptyNestedMap(Object element){ + boolean isEmpty = true; + if (element != null){ + if ( element instanceof Map ){ + if (MapUtils.isEmpty((Map)element)) + isEmpty = true; + else + { + for( Object key : ((Map)(element)).keySet() ){ + Object value = ((Map)(element)).get(key); + isEmpty &= isEmptyNestedMap( value ); + } + } + } else { + isEmpty = false; + } + } + return isEmpty; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java new file mode 100644 index 0000000000..e77287de9f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.components.property; + +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; + +public class GetInputUtils { + + private GetInputUtils() { + } + + public static boolean isGetInputValueForInput(GetInputValueDataDefinition inputData, String inputId) { + return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java new file mode 100644 index 0000000000..be3c82fa09 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java @@ -0,0 +1,130 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + +@org.springframework.stereotype.Component +public class PolicyPropertyDecelerator extends DefaultPropertyDecelerator<PolicyDefinition, PropertyDataDefinition> { + + private static final Logger log = LoggerFactory.getLogger(PolicyPropertyDecelerator.class); + private PolicyOperation policyOperation; + + public PolicyPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, PolicyOperation policyOperation) { + super(componentsUtils, propertyOperation); + this.policyOperation = policyOperation; + } + + @Override + PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + return new PropertyDataDefinition(prop); + } + + @Override + Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, List<PropertyDataDefinition> properties) { + log.debug("#updatePropertiesValues - updating policies properties for policy {} on component {}", policyId, component.getUniqueId()); + StorageOperationStatus updateStatus = policyOperation.updatePolicyProperties(component, policyId, properties); + return updateStatus == StorageOperationStatus.OK ? Either.left(updateStatus) : Either.right(updateStatus); + } + + @Override + Optional<PolicyDefinition> resolvePropertiesOwner(Component component, String policyId) { + log.debug("#resolvePropertiesOwner - fetching policy {} of component {}", policyId, component.getUniqueId()); + return Optional.ofNullable(component.getPolicyById(policyId)); + } + + @Override + void addPropertiesListToInput(PropertyDataDefinition declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List<ComponentInstanceProperty> propertiesList = input.getProperties(); + if(propertiesList == null) { + propertiesList = new ArrayList<>(); // adding the property with the new value for UI + } + propertiesList.add(new ComponentInstanceProperty(declaredProp)); + input.setProperties(propertiesList); + + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputForDelete) { + return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId()) + .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)) + .orElse(StorageOperationStatus.OK); + } + + private StorageOperationStatus unDeclarePolicyProperties(Component container, InputDefinition input, PolicyProperties policyProperties) { + String policyId = policyProperties.getPolicyId(); + List<PropertyDataDefinition> propsDeclaredAsInput = policyProperties.getProperties(); + propsDeclaredAsInput.forEach(policyProp -> prepareValueBeforeDelete(input, policyProp, Collections.emptyList())); + return policyOperation.updatePolicyProperties(container, policyId, propsDeclaredAsInput); + } + + private Optional<PolicyProperties> getPolicyPropertiesDeclaredAsInput(Component container, String inputId) { + if (container.getPolicies() == null) { + return Optional.empty(); + } + return container.getPolicies().values() + .stream() + .filter(policy -> Objects.nonNull(policy.getProperties())) + .collect(Collectors.toMap(PolicyDataDefinition::getUniqueId, + p -> getPolicyPropertiesDeclaredAsInput(p, inputId))) + .entrySet() + .stream() + .filter(entry -> !entry.getValue().isEmpty()) + .map(entry -> new PolicyProperties(entry.getKey(), entry.getValue())) + .findFirst(); + } + + private boolean isPropertyDeclaredAsInputByInputId(PropertyDataDefinition property, String inputId) { + if (CollectionUtils.isEmpty(property.getGetInputValues())) { + return false; + } + return property.getGetInputValues().stream() + .filter(Objects::nonNull) + .anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId)); + } + + private List<PropertyDataDefinition> getPolicyPropertiesDeclaredAsInput(PolicyDefinition policy, String inputId) { + return policy.getProperties() + .stream() + .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)) + .collect(Collectors.toList()); + } + + private class PolicyProperties { + private String policyId; + private List<PropertyDataDefinition> properties; + + PolicyProperties(String policyId, List<PropertyDataDefinition> properties) { + this.policyId = policyId; + this.properties = properties; + } + + String getPolicyId() { + return policyId; + } + + public List<PropertyDataDefinition> getProperties() { + return properties; + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java new file mode 100644 index 0000000000..ea311cebb5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java @@ -0,0 +1,66 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; + +@org.springframework.stereotype.Component +public class PropertyDecelerationOrchestrator { + + private static final Logger log = LoggerFactory.getLogger(PropertyDecelerationOrchestrator.class); + private ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator; + private ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator; + private PolicyPropertyDecelerator policyPropertyDecelerator; + private List<PropertyDecelerator> propertyDecelerators; + + public PropertyDecelerationOrchestrator(ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator, ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator, PolicyPropertyDecelerator policyPropertyDecelerator) { + this.componentInstanceInputPropertyDecelerator = componentInstanceInputPropertyDecelerator; + this.componentInstancePropertyDecelerator = componentInstancePropertyDecelerator; + this.policyPropertyDecelerator = policyPropertyDecelerator; + propertyDecelerators = Arrays.asList(componentInstanceInputPropertyDecelerator, componentInstancePropertyDecelerator, policyPropertyDecelerator); + } + + public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) { + PropertyDecelerator propertyDecelerator = getPropertyDecelerator(componentInstInputsMap); + Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); + return propertyDecelerator.declarePropertiesAsInputs(component, propsToDeclare.getLeft(), propsToDeclare.getRight()); + } + + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) { + log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId()); + for (PropertyDecelerator propertyDecelerator : propertyDecelerators) { + StorageOperationStatus storageOperationStatus = propertyDecelerator.unDeclarePropertiesAsInputs(component, inputToDelete); + if (StorageOperationStatus.OK != storageOperationStatus) { + log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); + return storageOperationStatus; + } + } + return StorageOperationStatus.OK; + + } + + private PropertyDecelerator getPropertyDecelerator(ComponentInstInputsMap componentInstInputsMap) { + if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceInputsMap())) { + return componentInstanceInputPropertyDecelerator; + } + if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceProperties())) { + return componentInstancePropertyDecelerator; + } + if (!MapUtils.isEmpty(componentInstInputsMap.getPolicyProperties())) { + return policyPropertyDecelerator; + } + throw new IllegalStateException("there are no properties selected for deceleration"); + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java new file mode 100644 index 0000000000..9255763f2c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; + +public interface PropertyDecelerator { + + /** + * creates a list of inputs from the given list of properties and updates the properties accordingly + * @param component the container + * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc) + * @param propsToDeclare the list of properties that are being declared as inputs + * @return the list of inputs that were created from the given properties + */ + Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare); + + /** + * returns the values of declared properties to each original state before it was declared as an input. + * this function is to be called when an input, that was created by declaring a property, is deleted. + * @param component the container of the input to be deleted + * @param input the input to be deleted + */ + StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java new file mode 100644 index 0000000000..df6cb3f6b9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.components.scheduledtasks; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +public abstract class AbstractScheduleTaskRunner { + private static final Logger log = LoggerFactory.getLogger(AbstractScheduleTaskRunner.class); + public abstract ExecutorService getExecutorService(); + + protected void shutdownExecutor() { + ExecutorService executorService = getExecutorService(); + if (executorService == null) + return; + + executorService.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { + executorService.shutdownNow(); // Cancel currently executing + // tasks + // Wait a while for tasks to respond to being cancelled + if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) + log.debug("Pool did not terminate"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + executorService.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java new file mode 100644 index 0000000000..a2659f4559 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.scheduledtasks; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.CleanComponentsConfiguration; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +@Component("asdcComponentsCleaner") +public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implements Runnable { + + private static final Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class); + + @javax.annotation.Resource + private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null; + + private List<NodeTypeEnum> componentsToClean; + private long cleaningIntervalInMinutes; + + private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1, + new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build()); + ScheduledFuture<?> scheduledFuture = null; + + @PostConstruct + public void init() { + log.info("Enter init method of AsdcComponentsCleaner"); + Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); + CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration(); + + if (cleanComponentsConfiguration == null) { + log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration"); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", + "fecth configuration"); + return; + + } + componentsToClean = new ArrayList<NodeTypeEnum>(); + List<String> components = cleanComponentsConfiguration.getComponentsToClean(); + if (components == null) { + log.info("no component were configured for cleaning"); + } + for (String component : components) { + NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component); + if (typeEnum != null) + componentsToClean.add(typeEnum); + } + + long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes(); + + if (intervalInMinutes < 1) { + log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default"); + intervalInMinutes = 60; + } + cleaningIntervalInMinutes = intervalInMinutes; + + startTask(); + + log.info("End init method of AsdcComponentsCleaner"); + } + + @PreDestroy + public void destroy() { + this.stopTask(); + shutdownExecutor(); + } + + public void startTask() { + + log.debug("start task for cleaning components"); + + try { + + if (scheduledService != null) { + log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes); + scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, + TimeUnit.MINUTES); + + } + } catch (Exception e) { + log.debug("unexpected error occured", e); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", + e.getMessage()); + + } + } + + private void stopTask() { + if (scheduledFuture != null) { + boolean cancelTaskSuccessfully = scheduledFuture.cancel(true); + log.debug("Stop cleaning task. result = {}", cancelTaskSuccessfully); + if (!cancelTaskSuccessfully) { + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", + "try to stop the polling task"); + } + scheduledFuture = null; + } + + } + + @Override + public void run() { + try { + componentsCleanBusinessLogic.cleanComponents(componentsToClean); + } catch (Exception e) { + log.error("unexpected error occured", e); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", + e.getMessage()); + } + + } + + @Override + public ExecutorService getExecutorService() { + return scheduledService; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java new file mode 100644 index 0000000000..a09a78165e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.scheduledtasks; + +import fj.data.Either; +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("componentsCleanBusinessLogic") +public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { + + @Autowired + private ResourceBusinessLogic resourceBusinessLogic; + + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + + private static final Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class); + + public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean) { + + Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents = new HashMap<NodeTypeEnum, Either<List<String>, ResponseFormat>>(); + + log.trace("start cleanComponents"); + for (NodeTypeEnum type : componentsToClean) { + switch (type) { + case Resource: + processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic); + break; + case Service: + processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic); + break; + default: + log.debug("{} component type does not have cleaning method defined", type); + break; + } + } + + log.trace("end cleanComponents"); + return cleanedComponents; + } + + private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) { + Either<List<String>, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents(); + if (deleteMarkedResources.isRight()) { + log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage()); + } else { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": "); + for (String id : deleteMarkedResources.left().value()) { + sb.append(id).append(", "); + } + log.debug(sb.toString()); + } + } + cleanedComponents.put(type, deleteMarkedResources); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java new file mode 100644 index 0000000000..eac4ecf813 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.scheduledtasks; + +import com.google.common.annotations.VisibleForTesting; +import fj.data.Either; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction; + +@Component("recoveryThreadManager") +public class RecoveryThreadManager extends AbstractScheduleTaskRunner { + + private static final Logger log = LoggerFactory.getLogger(RecoveryThreadManager.class); + @VisibleForTesting + FixEnvironmentTask task = new FixEnvironmentTask(); + + @Resource + private OperationalEnvironmentDao operationalEnvironmentDao; + + @Autowired + private EnvironmentsEngine environmentsEngine; + + private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(NumberUtils.INTEGER_ONE, + new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build()); + @VisibleForTesting + Integer allowedTimeBeforeStaleSec; + + @PostConstruct + public void init() { + log.debug("Enter init method of RecoveryThreadManager"); + final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager + .getConfigurationManager().getDistributionEngineConfiguration(); + Integer opEnvRecoveryIntervalSec = distributionEngineConfiguration.getOpEnvRecoveryIntervalSec(); + scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec, + TimeUnit.SECONDS); + this.allowedTimeBeforeStaleSec = distributionEngineConfiguration.getAllowedTimeBeforeStaleSec(); + log.debug("End init method of AsdcComponentsCleaner"); + } + + @PreDestroy + public void destroy() { + shutdownExecutor(); + } + + protected class FixEnvironmentTask implements Runnable { + @Override + public void run() { + try { + // Failed Envs + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherFailedEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED); + eitherFailedEnv.bimap(convertToFunction(this::handleFailedeEnvironmentsRecords), convertToFunction( + cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.FAILED, cassandraError))); + + // In-Progress Envs + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherInProgressEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS); + eitherInProgressEnv.bimap(convertToFunction(this::handleInProgressEnvironmentsRecords), + convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS, + cassandraError))); + + // Envs To Connect to UEB topics + Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherCompleteEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); + eitherCompleteEnv.bimap(convertToFunction(this::handleCompleteEnvironmentsRecords), convertToFunction( + cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.COMPLETED, cassandraError))); + + } catch (Exception e) { + log.debug("error while handling operational environments to be fixed :{}", e.getMessage(), e); + } + } + + private void handleCompleteEnvironmentsRecords(List<OperationalEnvironmentEntry> completeEnvironmentsRecords) { + if (!isEmpty(completeEnvironmentsRecords)) { + completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env)) + .forEach(opEnvEntry -> { + environmentsEngine.createUebTopicsForEnvironment(opEnvEntry); + environmentsEngine.addToMap(opEnvEntry); + }); + } + + } + + private void handleFailedeEnvironmentsRecords(List<OperationalEnvironmentEntry> failedEnvironmentsRecords) { + if (!isEmpty(failedEnvironmentsRecords)) { + failedEnvironmentsRecords.parallelStream() + .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env)); + } + + } + + private void handleInProgressEnvironmentsRecords(List<OperationalEnvironmentEntry> inProgressEnvList) { + if (!isEmpty(inProgressEnvList)) { + + long currentTimeMillis = System.currentTimeMillis(); + if (!isEmpty(inProgressEnvList)) { + List<OperationalEnvironmentEntry> staleInProgressEnvList = inProgressEnvList.stream() + .filter(record -> (record.getLastModified().getTime() + (allowedTimeBeforeStaleSec * 1000)) < currentTimeMillis) + .collect(Collectors.toList()); + staleInProgressEnvList.parallelStream() + .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env)); + } + + } + + } + + private void logFailedRetrieveRecord(EnvironmentStatusEnum recordStatus, CassandraOperationStatus error) { + log.debug("error: {} while retrieving operational environments with status: {}", error, recordStatus); + } + + + } + + @Override + public ExecutorService getExecutorService() { + return scheduledService; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java new file mode 100644 index 0000000000..83f5a5de95 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.components.utils; + +import org.apache.tinkerpop.shaded.minlog.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.validation.constraints.NotNull; +import java.security.SecureRandom; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Utils { + + private static final Logger log = LoggerFactory.getLogger(Utils.class); + private static final Pattern COUNTER_PATTERN = Pattern.compile("\\d+$"); + private static final SecureRandom random = new SecureRandom(); + + + private Utils() {} + + public static int getNextCounter(@NotNull List<String> existingValues) { + if (existingValues.isEmpty()) { + return 0; + } + int maxCurrentCounter = 0; + try { + maxCurrentCounter = existingValues.stream() + .map(COUNTER_PATTERN::matcher) + .filter(Matcher::find) + .map(matcher -> matcher.group(0)) + .mapToInt(Integer::parseInt) + .max() + .orElse(0); + } + catch (Exception e) { + Log.warn("Failed in retrieivng counter from existing value: ", e); + maxCurrentCounter = random.nextInt(100) + 50; + } + return ++maxCurrentCounter; + } +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java new file mode 100644 index 0000000000..da098acb13 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +@org.springframework.stereotype.Component +public class AccessValidations { + + private final UserValidations userValidations; + private final ComponentValidations componentValidations; + + + public AccessValidations(UserValidations userValidations, ComponentValidations componentValidations) { + this.userValidations = userValidations; + this.componentValidations = componentValidations; + } + + public Component validateUserCanWorkOnComponentAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId, String actionContext) { + userValidations.validateUserExists(userId, actionContext, false) + .left() + .on(this::onUserError); + + return componentValidations.validateComponentIsCheckedOutByUserAndLockIt(componentTypeEnum, componentId, userId); + } + + private User onUserError(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java new file mode 100644 index 0000000000..c626e29f21 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.validation; + +/** + * Created by chaya on 11/14/2017. + */ +public enum ApiResourceEnum { + + ENVIRONMENT_ID("Environment ID"), + RESOURCE_ID("Resource ID"), + SERVICE_ID("Service ID"); + + private String value; + + ApiResourceEnum(String value) { + this.value = value; + } + + public String getValue() { + return this.value; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java index 15fff52ab9..002ae50cde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java @@ -20,19 +20,126 @@ package org.openecomp.sdc.be.components.validation; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; +import java.util.Set; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; +import org.openecomp.sdc.common.util.ValidationUtils; -public class ComponentValidations { +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static java.util.stream.Collectors.toList; + + +@org.springframework.stereotype.Component +public final class ComponentValidations { + + private final ToscaOperationFacade toscaOperationFacade; + private final IGraphLockOperation graphLockOperation; + + public ComponentValidations(ToscaOperationFacade toscaOperationFacade, IGraphLockOperation graphLockOperation) { + this.toscaOperationFacade = toscaOperationFacade; + this.graphLockOperation = graphLockOperation; + } public static boolean validateComponentInstanceExist(Component component, String instanceId) { return Optional.ofNullable(component.getComponentInstances()) - .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(Collectors.toList())) + .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList())) .filter(instancesIds -> instancesIds.contains(instanceId)) .isPresent(); } + public static String getNormalizedName(ToscaDataDefinition toscaDataDefinition) { + String name = (String) toscaDataDefinition.getToscaPresentationValue(JsonPresentationFields.NAME); + return org.openecomp.sdc.common.util.ValidationUtils.normalizeComponentInstanceName(name); + } + + /** + * The following logic is applied: + * For each name new or existing name we look at the normalized name which is used in Tosca representation + * @param currentName + * @param newName + * @param component + * @return True is new name can be used in this component, false otherwise + */ + public static boolean validateNameIsUniqueInComponent(String currentName, String newName, Component component) { + String normalizedCurrentName = ValidationUtils.normalizeComponentInstanceName(currentName); + String normalizedNewName = ValidationUtils.normalizeComponentInstanceName(newName); + + if (normalizedCurrentName.equals(normalizedNewName)) { + return true; //As it's same entity, still considered unique + } + List<GroupDefinition> groups = component.getGroups(); + List<ComponentInstance> componentInstances = component.getComponentInstances(); + Set<String> existingNames = new HashSet<>(); + if (CollectionUtils.isNotEmpty(groups)) { + List<String> existingGroupNames = groups + .stream() + .map(ComponentValidations::getNormalizedName) + .collect(toList()); + existingNames.addAll(existingGroupNames); + } + if (CollectionUtils.isNotEmpty(componentInstances)) { + List<String> existingInstanceNames = componentInstances + .stream() + .map(ComponentValidations::getNormalizedName) + .collect(toList()); + existingNames.addAll(existingInstanceNames); + } + return !existingNames.contains(normalizedNewName); + } + + public Component validateComponentIsCheckedOutByUserAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId) { + Component component = getComponent(componentId, componentTypeEnum); + + if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { + throw new ComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getName()); + } + + lockComponent(component); + + return component; + } + + private Component getComponent(String componentId, ComponentTypeEnum componentType) { + Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()) + .left() + .on(this::onToscaOperationError); + + if (componentType!=component.getComponentType()) { + throw new ComponentException(ActionStatus.INVALID_RESOURCE_TYPE); + } + + return component; + } + + private void lockComponent(Component component) { + StorageOperationStatus lockComponentStatus = graphLockOperation.lockComponent(component.getUniqueId(), + component.getComponentType().getNodeType()); + if (!StorageOperationStatus.OK.equals(lockComponentStatus)) { + throw new StorageException(lockComponentStatus); + } + } + + private Component onToscaOperationError(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java new file mode 100644 index 0000000000..c1934ae1c4 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java @@ -0,0 +1,216 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Provides specific functionality for policy + */ +public class PolicyUtils { + + private static final Logger log = LoggerFactory.getLogger(PolicyUtils.class); + + private PolicyUtils() { + // No instances allowed + } + + /** + * Calculates the next integer counter according to the found max counter existing in the provided policies map + * + * @param policies the map of the policies + * @return the integer counter + */ + public static int getNextPolicyCounter(Map<String, PolicyDefinition> policies) { + int nextCounter = 0; + if (MapUtils.isNotEmpty(policies)) { + int nextCounterFromIds = policies.values() + .stream() + .map(p -> extractNextPolicyCounterFromUniqueId(p.getUniqueId())) + .max(Integer::compareTo) + .orElse(0); + int nextCounterFromNames = policies.values() + .stream() + .map(p -> extractNextPolicyCounterFromName(p.getName())) + .max(Integer::compareTo) + .orElse(0); + nextCounter = nextCounterFromIds > nextCounterFromNames ? nextCounterFromIds : nextCounterFromNames; + } + return nextCounter; + } + + /** + * Validates policy fields on policy update. Updates mutable fields + * + * @param recievedPolicy the policy parsed from the HTTP request + * @param validPolicy the copy of the existing policy found on the component + * @param policies all the polices related to the component + * @return validated and updated policy or an error as action status + */ + public static Either<PolicyDefinition, ActionStatus> validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) { + validateImmutablePolicyFields(recievedPolicy, validPolicy); + return validateUpdateMutablePolicyFields(recievedPolicy, validPolicy, policies); + } + + /** + * Retrieves the set of the excluded policy types for the specified component + * + * @param the component + * @return the set of the policies + */ + public static Set<String> getExcludedPolicyTypesByComponent(Component component) { + if (MapUtils.isEmpty(ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping())) { + return Collections.emptySet(); + } + if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + return ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping() + .get(component.getComponentType().name()); + } + return ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping() + .get(((Resource) component).getResourceType().getValue()); + } + + private static int extractNextPolicyCounterFromUniqueId(String uniqueId) { + int counter = 0; + if (StringUtils.isNotEmpty(uniqueId)) { + counter = extractNextPolicyCounter(uniqueId, uniqueId.lastIndexOf(Constants.POLICY_UID_POSTFIX)); + } + return counter; + } + + private static int extractNextPolicyCounterFromName(String policyName) { + int counter = 0; + if (StringUtils.isNotEmpty(policyName)) { + counter = extractNextPolicyCounter(policyName, policyName.length()); + } + return counter; + } + + private static int extractNextPolicyCounter(String policyName, int endIndex) { + int counter = 0; + try { + counter = Integer.valueOf(policyName.substring(policyName.lastIndexOf(Constants.GROUP_POLICY_NAME_DELIMETER) + Constants.GROUP_POLICY_NAME_DELIMETER + .length(), endIndex)) + 1; + } + catch (NumberFormatException | IndexOutOfBoundsException e) { + log.error("The exception {} occurred upon extraction counter from the srting value {}. ", e, policyName); + } + return counter; + } + + private static Either<PolicyDefinition, ActionStatus> validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) { + return validateUpdatePolicyName(recievedPolicy, validPolicy, policies); + } + + private static void validateImmutablePolicyFields(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy) { + boolean isUpdatedField = isUpdatedField(receivedPolicy.getUniqueId(), validPolicy.getUniqueId()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getUniqueId(), validPolicy.getUniqueId(), JsonPresentationFields.UNIQUE_ID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getComponentName(), validPolicy.getComponentName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getComponentName(), validPolicy.getComponentName(), JsonPresentationFields.CI_COMPONENT_NAME); + } + isUpdatedField = isUpdatedField(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom(), JsonPresentationFields.DERIVED_FROM); + } + isUpdatedField = isUpdatedField(receivedPolicy.getDescription(), validPolicy.getDescription()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getDescription(), validPolicy.getDescription(), JsonPresentationFields.DESCRIPTION); + } + isUpdatedField = isUpdatedField(receivedPolicy.getInvariantName(), validPolicy.getInvariantName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getInvariantName(), validPolicy.getInvariantName(), JsonPresentationFields.CI_INVARIANT_NAME); + } + isUpdatedField = isUpdatedField(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID(), JsonPresentationFields.INVARIANT_UUID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName(), JsonPresentationFields.TYPE); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid(), JsonPresentationFields.TYPE_UNIQUE_ID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID(), JsonPresentationFields.UUID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getVersion(), validPolicy.getVersion()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getVersion(), validPolicy.getVersion(), JsonPresentationFields.VERSION); + } + isUpdatedField = isUpdatedField(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar() + .toString()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar() + .toString(), JsonPresentationFields.IS_FROM_CSAR); + } + } + + private static boolean isUpdatedField(String oldField, String newField) { + boolean isUpdatedField = false; + if (StringUtils.isEmpty(oldField) && StringUtils.isNotEmpty(newField)) { + isUpdatedField = true; + } + if (StringUtils.isNotEmpty(oldField) && StringUtils.isNotEmpty(newField) && !oldField.equals(newField)) { + isUpdatedField = true; + } + return isUpdatedField; + } + + private static void logImmutableFieldUpdateWarning(String oldValue, String newValue, JsonPresentationFields field) { + log.warn("Update of the field {} of a policy not allowed. The change will be ignored. The old value is {} , the new value is {}. ", field, oldValue, newValue); + } + + private static Either<PolicyDefinition, ActionStatus> validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) { + Either<PolicyDefinition, ActionStatus> result = null; + Optional<PolicyDefinition> sameNamePolicy = Optional.empty(); + if (StringUtils.isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy + .getName()).matches()) { + log.error("Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), receivedPolicy.getUniqueId()); + result = Either.right(ActionStatus.INVALID_POLICY_NAME); + } + if (result == null && MapUtils.isNotEmpty(policies)) { + sameNamePolicy = policies.values() + .stream() + .filter(p -> p.getName().equals(receivedPolicy.getName())) + .findFirst(); + } + if (sameNamePolicy.isPresent()) { + log.error("Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ", receivedPolicy + .getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId()); + result = Either.right(ActionStatus.POLICY_NAME_ALREADY_EXIST); + } + if (result == null) { + validPolicy.setName(receivedPolicy.getName()); + result = Either.left(validPolicy); + } + return result; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java new file mode 100644 index 0000000000..ec5a1c3078 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java @@ -0,0 +1,118 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.List; + +/** + * Created by chaya on 10/18/2017. + */ +@org.springframework.stereotype.Component("serviceDistributionValidation") +public class ServiceDistributionValidation { + private static final Logger log = LoggerFactory.getLogger(ServiceDistributionValidation.class); + @Resource + private ComponentsUtils componentsUtils; + @Resource + private ToscaOperationFacade toscaOperationFacade; + @Resource + private UserValidations userValidations; + @Resource + private IDistributionEngine distributionEngine; + + public Either<ActivationRequestInformation, ResponseFormat> validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier, ServiceDistributionReqInfo data) { + try { + validateUserExists(modifier.getUserId()); + Service serviceToActivate = validateServiceExists(serviceUUID); + validateDistributionServiceLifeCycleState(serviceToActivate); + OperationalEnvironmentEntry operationalEnvironmentEntry = validateOperationalEnvExists(opEnvId); + String workloadContext = validateWorkloadContext(data); + ActivationRequestInformation activationRequestInformation = new ActivationRequestInformation(serviceToActivate, workloadContext, operationalEnvironmentEntry.getTenant()); + return Either.left(activationRequestInformation); + } catch (ValidationException e) { + log.error("failed while validating activate service UUID {} request. error {}", serviceUUID, e.getExceptionResponseFormat(), e); + return Either.right(e.getExceptionResponseFormat()); + } + } + + private Service validateServiceExists(String serviceUUID) { + if (StringUtils.isEmpty(serviceUUID.trim())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE); + throw new ValidationException(responseFormat); + } + Either<Component, StorageOperationStatus> latestComponentByUuid = toscaOperationFacade.getLatestServiceByUuid(serviceUUID); + if (latestComponentByUuid.isRight()) { + log.error("failed retrieving service {}", serviceUUID); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue()); + throw new ValidationException(responseFormat); + } + return (Service)latestComponentByUuid.left().value(); + } + + private String validateWorkloadContext(ServiceDistributionReqInfo data) { + String workloadContext = data.getWorkloadContext(); + if (workloadContext == null || workloadContext.isEmpty()) { + log.error("workload context does not exist on data to distribute"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_BODY); + throw new ValidationException(responseFormat); + } + return workloadContext; + } + + private OperationalEnvironmentEntry validateOperationalEnvExists(String opEnvId) { + if (StringUtils.isEmpty(opEnvId.trim())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE); + throw new ValidationException(responseFormat); + } + OperationalEnvironmentEntry operationalEnvironment = distributionEngine.getEnvironmentById(opEnvId); + if (operationalEnvironment == null) { + return failOnEnvNotExist(opEnvId); + } + if (!operationalEnvironment.getStatus().equals(EnvironmentStatusEnum.COMPLETED.getName())) { + log.error("the operational environment is not ready to receive distributions. environment status: {}", operationalEnvironment.getStatus()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND , ApiResourceEnum.ENVIRONMENT_ID.getValue()); + throw new ValidationException(responseFormat); + } + return operationalEnvironment; + } + + private OperationalEnvironmentEntry failOnEnvNotExist(String opEnvId) { + return ValidationUtils.throwValidationException(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue()), "failed to get operational environment {}", opEnvId); + } + + private void validateServiceState(Service service, List<LifecycleStateEnum> allowedStates) { + LifecycleStateEnum state = service.getLifecycleState(); + if (!allowedStates.contains(state)) { + log.error("service {} life cycle state {} is not valid for distribution", service.getUniqueId(), service.getLifecycleState()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_STATE); + throw new ValidationException(responseFormat); + } + } + private void validateUserExists(String userId) { + userValidations.validateUserExists(userId, "activate Distribution", false) + .left().on(responseFormat -> ValidationUtils.throwValidationException(responseFormat, "user {} not exist", userId)); + } + + private void validateDistributionServiceLifeCycleState(Service serviceToActivate) { + validateServiceState(serviceToActivate, + Arrays.asList(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFIED)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java new file mode 100644 index 0000000000..e2e671f872 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.IUserBusinessLogic; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +@org.springframework.stereotype.Component +public class UserValidations { + + private static final Logger log = LoggerFactory.getLogger(UserValidations.class); + private final IUserBusinessLogic userAdmin; + private final ComponentsUtils componentsUtils; + + public UserValidations(IUserBusinessLogic userAdmin, ComponentsUtils componentsUtils) { + this.userAdmin = userAdmin; + this.componentsUtils = componentsUtils; + } + + public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { + Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, inTransaction); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + ResponseFormat responseFormat; + if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + if (log.isDebugEnabled()) { + log.debug("validateUserExists - not authorized user, userId {}", userId); + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.AUTH_FAILED); + } else { + if (log.isDebugEnabled()) { + log.debug("validateUserExists - failed to authorize user, userId {}", userId); + } + responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value()); + } + if (log.isDebugEnabled()) { + log.debug("User is not listed. userId {}", userId); + } + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); + return Either.right(responseFormat); + } + return Either.left(eitherCreator.left().value()); + } + + public Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) { + Role userRole = Role.valueOf(user.getRole()); + if (roles != null) { + if (!roles.contains(userRole)) { + if (log.isDebugEnabled()) { + log.debug("user is not in appropriate role to perform action"); + } + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + return Either.left(Boolean.TRUE); + } + return Either.left(Boolean.FALSE); + } + + public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) { + Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("validateUserExists - not authorized user, userId {}", userId); + Either.right(ActionStatus.RESTRICTED_OPERATION); + } else { + log.debug("validateUserExists - failed to authorize user, userId {}", userId); + } + log.debug("User is not listed. userId {}", userId); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); + return Either.right(eitherCreator.right().value()); + } + return Either.left(eitherCreator.left().value()); + } + + public Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) { + String userId = user.getUserId(); + + if (StringUtils.isEmpty(userId)) { + log.debug("User header is missing "); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + return Either.right(responseFormat); + } + return Either.left(user); + } + + public Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { + return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); + } + + public void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) { + Either<User, ResponseFormat> resp = validateUserExists(userId, ecompErrorContext, false); + if (resp.isRight()) { + errorWrapper.setInnerElement(resp.right().value()); + } + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java new file mode 100644 index 0000000000..8abf2f7d63 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.exception.ResponseFormat; + +/** + * Created by chaya on 10/18/2017. + */ +public class ValidationException extends RuntimeException { + + private transient ResponseFormat exceptionResponseFormat; + + public ValidationException(ResponseFormat exceptionResponseFormat) { + super(); + this.exceptionResponseFormat = exceptionResponseFormat; + } + + public ResponseFormat getExceptionResponseFormat() { + return exceptionResponseFormat; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java new file mode 100644 index 0000000000..07505a2adb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ValidationUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(ValidationUtils.class); + + public static <T> T throwValidationException(ResponseFormat responseFormat, String logMessage, Object ... logParams){ + LOGGER.error(logMessage, logParams); + throw new ValidationException(responseFormat); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java new file mode 100644 index 0000000000..967232ac86 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.Set; + +public class ForwardingPaths implements Serializable{ + + private static final long serialVersionUID=1L; + + public ForwardingPaths() { + } + + private Set<String> forwardingPathToDelete; + public Set<String> getForwardingPathToDelete() { + return forwardingPathToDelete; + } + + public void setForwardingPathToDelete(Set<String> forwardingPathToDelete) { + this.forwardingPathToDelete = forwardingPathToDelete; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java new file mode 100644 index 0000000000..a033cec86f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java @@ -0,0 +1,89 @@ +package org.openecomp.sdc.be.datamodel; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +public class NameIdPair extends HashMap<String, Object> implements java.io.Serializable { + public static final String OPTIONS = "options"; + public static final String NAME = "name"; + public static final String ID = "id"; + public static final String OWNER_ID = "ownerId"; + + public NameIdPair(String name, String id) { + this(name, id, null); + } + + public NameIdPair(String name, String id, String ownerId) { + super(); + setId(id); + setName(name); + if (!Objects.isNull(ownerId)) { + setOwnerId(ownerId); + } + + } + + public NameIdPair(NameIdPair nameIdPair) { + super(nameIdPair); + } + + public String getName() { + return get(NAME).toString(); + } + + public void setName(String name) { + super.put(NAME, name); + } + + public String getId() { + return get(ID).toString(); + } + + public void setId(String id) { + super.put(ID, id); + } + + public String getOwnerId() { + return get(OWNER_ID).toString(); + } + + public void setOwnerId(String ownerId) { + put(OWNER_ID, ownerId); + } + + public Set<NameIdPairWrapper> getWrappedData() { + return (Set<NameIdPairWrapper>) super.get(OPTIONS); + } + + public void setWrappedData(Set<NameIdPairWrapper> data) { + super.put(OPTIONS, data); + } + + public void addWrappedData(NameIdPairWrapper nameIdPairWrapper) { + if (get(OPTIONS) == null) { + setWrappedData(new HashSet<>()); + } + getWrappedData().add(nameIdPairWrapper); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof NameIdPair)) return false; + NameIdPair that = (NameIdPair) o; + return Objects.equals(getId(), that.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } + + public static final NameIdPair create(String name, String id) { + return new NameIdPair(name, id); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java new file mode 100644 index 0000000000..e46e57705e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.HashMap; + +public class NameIdPairWrapper extends HashMap<String, Object> implements Serializable { + public static final String ID = "id"; + public static final String DATA = "data"; + + public NameIdPairWrapper() { + } + + public NameIdPairWrapper(NameIdPair nameIdPair) { + super(); + init(nameIdPair); + } + public void init(NameIdPair nameIdPair) { + setId(nameIdPair.getId()); + setData(new NameIdPair(nameIdPair)); + } + + public String getId() { + return get(ID).toString(); + } + + public void setId(String id) { + super.put(ID, id); + } + + public NameIdPair getData() { + return (NameIdPair) get(DATA); + } + + public void setData(NameIdPair data) { + put(DATA, data); + } + + public NameIdPair getNameIdPair(){ + return new NameIdPair(getData().getName(),getData().getId()); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java new file mode 100644 index 0000000000..d05ddafed9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.Set; + +public class ServiceRelations extends java.util.HashSet<NameIdPairWrapper> implements Serializable { + + + + public ServiceRelations() { + } + + public ServiceRelations(Set<NameIdPairWrapper> relations) { + super(); + addAll(relations); + } + + public Set<NameIdPairWrapper> getRelations() { + return this; + } + + public void setRelations(Set<NameIdPairWrapper> relations) { + clear(); + this.addAll(relations); + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java index 921aefaa8e..855f20aba2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java @@ -24,16 +24,16 @@ import java.io.Serializable; public enum CategoryTypeEnum implements Serializable { - CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); + CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); - private String value; + private String value; - CategoryTypeEnum(String value) { - this.value = value; - } + CategoryTypeEnum(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java index 42ff4c900a..fc98400dd1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java @@ -22,6 +22,6 @@ package org.openecomp.sdc.be.datamodel.api; public enum HighestFilterEnum { - ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY; + ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java index 9f66911461..9f0d7a3281 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java @@ -20,39 +20,121 @@ package org.openecomp.sdc.be.datamodel.utils; +import org.apache.commons.codec.binary.Base64; +import org.openecomp.sdc.be.info.ArtifactTemplateInfo; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.stream.Collectors; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; - +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; public class ArtifactUtils { - public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) { - for (String artifactUid : artifactsList) { - for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) { - ArtifactDefinition artifact = entry.getValue(); - if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) { - artifacts.add(artifact); - } - - } - } - if (artifacts.size() == 1) { - return artifacts.get(0); - } - ArtifactDefinition masterArtifact = null; - for (ArtifactDefinition artifactInfo : artifacts) { - String atrifactType = artifactInfo.getArtifactType(); - if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { - masterArtifact = artifactInfo; - continue; - } - if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - masterArtifact = artifactInfo; - break; - } - } - return masterArtifact; - } + + public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) { + for (String artifactUid : artifactsList) { + for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) { + ArtifactDefinition artifact = entry.getValue(); + if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) { + artifacts.add(artifact); + } + + } + } + if (artifacts.size() == 1) { + return artifacts.get(0); + } + ArtifactDefinition masterArtifact = null; + for (ArtifactDefinition artifactInfo : artifacts) { + String atrifactType = artifactInfo.getArtifactType(); + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { + masterArtifact = artifactInfo; + continue; + } + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + masterArtifact = artifactInfo; + break; + } + } + return masterArtifact; + } + + public static Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, + ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, + byte[] artifactContentent, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean isFromCsar) { + + Map<String, Object> json = new HashMap<String, Object>(); + if (artifactId != null && !artifactId.isEmpty()) + json.put(Constants.ARTIFACT_ID, artifactId); + + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_TYPE, artifactType); + json.put(Constants.ARTIFACT_DESCRIPTION, description); + json.put(Constants.IS_FROM_CSAR, isFromCsar); + + String encodedPayload = new String(artifactContentent); + + + encodedPayload = Base64.encodeBase64String(artifactContentent); + // } + + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); + json.put(Constants.REQUIRED_ARTIFACTS, + (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() + : updatedRequiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) + || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()).collect(Collectors.toList())); + return json; + } + + public static Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, + byte[] artifactContentent, int atrifactLabelCounter) { + + Map<String, Object> json = new HashMap<String, Object>(); + String artifactName = artifactTemplateInfo.getFileName(); + + json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName()); + json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType()); + json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar"); + + String encodedPayload = Base64.encodeBase64String(artifactContentent); + + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + String displayName = artifactName; + if (artifactName.lastIndexOf(".") > 0) + displayName = artifactName.substring(0, artifactName.lastIndexOf(".")); + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + json.put(Constants.REQUIRED_ARTIFACTS, + (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>() + : requiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) + || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()).collect(Collectors.toList())); + return json; + } + + public static ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) { + for (ArtifactDefinition artifact : createdArtifacts) { + if (artifact.getUniqueId().equals(artifactId)) { + return artifact; + } + } + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java index ab71508e62..cd6351cf9e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java @@ -25,52 +25,52 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; public class NodeTypeConvertUtils { - public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) { - NodeTypeEnum res = null; - if (componentTypeEnum != null) { - switch (componentTypeEnum) { - case SERVICE: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ServiceNewCategory; - break; + public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) { + NodeTypeEnum res = null; + if (componentTypeEnum != null) { + switch (componentTypeEnum) { + case SERVICE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ServiceNewCategory; + break; - default: - // doesn't support subcategories or grouping - break; - } - break; - case RESOURCE: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ResourceNewCategory; - break; - case SUBCATEGORY: - res = NodeTypeEnum.ResourceSubcategory; - break; - default: - // doesn't support grouping - break; - } - break; - case PRODUCT: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ProductCategory; - break; - case SUBCATEGORY: - res = NodeTypeEnum.ProductSubcategory; - break; - case GROUPING: - res = NodeTypeEnum.ProductGrouping; - break; - } - break; - default: - break; - } - } - return res; - } + default: + // doesn't support subcategories or grouping + break; + } + break; + case RESOURCE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ResourceNewCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ResourceSubcategory; + break; + default: + // doesn't support grouping + break; + } + break; + case PRODUCT: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ProductCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ProductSubcategory; + break; + case GROUPING: + res = NodeTypeEnum.ProductGrouping; + break; + } + break; + default: + break; + } + } + return res; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java index f2a5b35562..624a8b623a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -20,236 +20,243 @@ package org.openecomp.sdc.be.datamodel.utils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; -import org.openecomp.sdc.be.ui.model.UiComponentMetadata; -import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; -import org.openecomp.sdc.be.ui.model.UiResourceMetadata; -import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; -import org.openecomp.sdc.be.ui.model.UiServiceMetadata; +import org.openecomp.sdc.be.ui.model.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; public class UiComponentDataConverter { - - public static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case INPUTS: - if(component.getInputs() == null){ - dataTransfer.setInputs(new ArrayList<>()); - } else { - dataTransfer.setInputs(component.getInputs()); - } - break; - - case COMPONENT_INSTANCE_RELATION: - if(component.getComponentInstancesRelations() == null){ - dataTransfer.setComponentInstancesRelations(new ArrayList<>()); - } else { - dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations()); - } - - break; - - case GROUPS: - if(component.getGroups() == null){ - dataTransfer.setGroups(new ArrayList<>()); - } else { - dataTransfer.setGroups(component.getGroups()); - } - break; - - case COMPONENT_INSTANCES: - if(component.getComponentInstances() == null) { - dataTransfer.setComponentInstances(new ArrayList<>()); - } else { - dataTransfer.setComponentInstances(component.getComponentInstances()); - } - break; - - case COMPONENT_INSTANCES_PROPERTIES: - if(component.getComponentInstancesProperties() == null) { - dataTransfer.setComponentInstancesProperties(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties()); - } - break; - - case CAPABILITIES: - if(component.getCapabilities() == null) { - dataTransfer.setCapabilities(new HashMap<>()); - } else { - dataTransfer.setCapabilities(component.getCapabilities()); - } - break; - - case REQUIREMENTS: - if(component.getRequirements() == null) { - dataTransfer.setRequirements(new HashMap<>()); - } else { - dataTransfer.setRequirements(component.getRequirements()); - } - break; - - case DEPLOYMENT_ARTIFACTS: - if(component.getDeploymentArtifacts() == null) { - dataTransfer.setDeploymentArtifacts(new HashMap<>()); - } else { - dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts()); - } - break; - - case TOSCA_ARTIFACTS: - if(component.getToscaArtifacts() == null) { - dataTransfer.setToscaArtifacts(new HashMap<>()); - } else { - dataTransfer.setToscaArtifacts(component.getToscaArtifacts()); - } - break; - - case ARTIFACTS: - if(component.getArtifacts() == null) { - dataTransfer.setArtifacts(new HashMap<>()); - } else { - dataTransfer.setArtifacts(component.getArtifacts()); - } - break; - - case COMPONENT_INSTANCES_ATTRIBUTES: - if(component.getComponentInstancesAttributes() == null) { - dataTransfer.setComponentInstancesAttributes(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes()); - } - break; - - case COMPONENT_INSTANCE_INPUTS: - if(component.getComponentInstancesInputs() == null) { - dataTransfer.setComponentInstancesInputs(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs()); - } - - break; - - - default: - break; - } - - } - - - public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) { - UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); - - for(String fieldName: paramsToReturn){ - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case PROPERTIES: - if(resource.getProperties() == null) { - dataTransfer.setProperties(new ArrayList<>()); - } else { - dataTransfer.setProperties(resource.getProperties()); - } - break; - - case INTERFACES: - if(resource.getInterfaces() == null) { - dataTransfer.setInterfaces(new HashMap<>()); - } else { - dataTransfer.setInterfaces(resource.getInterfaces()); - } - break; - - case DERIVED_FROM: - if(resource.getDerivedFrom() == null) { - dataTransfer.setDerivedFrom(new ArrayList<>()); - } else { - dataTransfer.setDerivedFrom(resource.getDerivedFrom()); - } - break; - - case ATTRIBUTES: - if(resource.getAttributes() == null) { - dataTransfer.setAttributes(new ArrayList<>()); - } else { - dataTransfer.setAttributes(resource.getAttributes()); - } - break; - - case ADDITIONAL_INFORMATION: - if(resource.getAdditionalInformation() == null) { - dataTransfer.setAdditionalInformation(new ArrayList<>()); - } else { - dataTransfer.setAdditionalInformation(resource.getAdditionalInformation()); - } - break; - case METADATA: - UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); - dataTransfer.setMetadata(metadata); - break; - - default: - setUiTranferDataByFieldName(dataTransfer, resource, fieldName); - } - } - - return dataTransfer; - } - - public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List<String> paramsToReturn) { - UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer(); - - for(String fieldName: paramsToReturn){ - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case SERVICE_API_ARTIFACTS: - if(service.getServiceApiArtifacts() == null) { - dataTransfer.setServiceApiArtifacts(new HashMap<>()); - } else { - dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts()); - } - - break; - - case METADATA: - UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); - dataTransfer.setMetadata(metadata); - break; - default: - setUiTranferDataByFieldName(dataTransfer, service, fieldName); - } - } - - return dataTransfer; - } - - - public static UiComponentMetadata convertToUiComponentMetadata(Component component) { - - UiComponentMetadata uiComponentMetadata = null; - switch (component.getComponentType()) { - case RESOURCE: - Resource resource = (Resource)component; - uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); - break; - case SERVICE: - uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); - default: - - } - return uiComponentMetadata; - } + + private static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case INPUTS: + if(component.getInputs() == null){ + dataTransfer.setInputs(new ArrayList<>()); + } else { + dataTransfer.setInputs(component.getInputs()); + } + break; + + case COMPONENT_INSTANCE_RELATION: + if(component.getComponentInstancesRelations() == null){ + dataTransfer.setComponentInstancesRelations(new ArrayList<>()); + } else { + dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations()); + } + + break; + + case GROUPS: + if(component.getGroups() == null){ + dataTransfer.setGroups(new ArrayList<>()); + } else { + dataTransfer.setGroups(component.getGroups()); + } + break; + + case COMPONENT_INSTANCES: + if(component.getComponentInstances() == null) { + dataTransfer.setComponentInstances(new ArrayList<>()); + } else { + dataTransfer.setComponentInstances(component.getComponentInstances()); + } + break; + + case COMPONENT_INSTANCES_PROPERTIES: + if(component.getComponentInstancesProperties() == null) { + dataTransfer.setComponentInstancesProperties(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties()); + } + break; + + case CAPABILITIES: + if(component.getCapabilities() == null) { + dataTransfer.setCapabilities(new HashMap<>()); + } else { + dataTransfer.setCapabilities(component.getCapabilities()); + } + break; + + case POLICIES: + dataTransfer.setPolicies(component.resolvePoliciesList()); + break; + + case REQUIREMENTS: + if(component.getRequirements() == null) { + dataTransfer.setRequirements(new HashMap<>()); + } else { + dataTransfer.setRequirements(component.getRequirements()); + } + break; + + case DEPLOYMENT_ARTIFACTS: + if(component.getDeploymentArtifacts() == null) { + dataTransfer.setDeploymentArtifacts(new HashMap<>()); + } else { + dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts()); + } + break; + + case TOSCA_ARTIFACTS: + if(component.getToscaArtifacts() == null) { + dataTransfer.setToscaArtifacts(new HashMap<>()); + } else { + dataTransfer.setToscaArtifacts(component.getToscaArtifacts()); + } + break; + + case ARTIFACTS: + if(component.getArtifacts() == null) { + dataTransfer.setArtifacts(new HashMap<>()); + } else { + dataTransfer.setArtifacts(component.getArtifacts()); + } + break; + + case COMPONENT_INSTANCES_ATTRIBUTES: + if(component.getComponentInstancesAttributes() == null) { + dataTransfer.setComponentInstancesAttributes(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes()); + } + break; + + case COMPONENT_INSTANCE_INPUTS: + if(component.getComponentInstancesInputs() == null) { + dataTransfer.setComponentInstancesInputs(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs()); + } + + break; + + + default: + break; + } + + } + + + public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) { + UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case PROPERTIES: + if(resource.getProperties() == null) { + dataTransfer.setProperties(new ArrayList<>()); + } else { + dataTransfer.setProperties(resource.getProperties()); + } + break; + + case INTERFACES: + if(resource.getInterfaces() == null) { + dataTransfer.setInterfaces(new HashMap<>()); + } else { + dataTransfer.setInterfaces(resource.getInterfaces()); + } + break; + + case DERIVED_FROM: + if(resource.getDerivedFrom() == null) { + dataTransfer.setDerivedFrom(new ArrayList<>()); + } else { + dataTransfer.setDerivedFrom(resource.getDerivedFrom()); + } + break; + + case ATTRIBUTES: + if(resource.getAttributes() == null) { + dataTransfer.setAttributes(new ArrayList<>()); + } else { + dataTransfer.setAttributes(resource.getAttributes()); + } + break; + + case ADDITIONAL_INFORMATION: + if(resource.getAdditionalInformation() == null) { + dataTransfer.setAdditionalInformation(new ArrayList<>()); + } else { + dataTransfer.setAdditionalInformation(resource.getAdditionalInformation()); + } + break; + case METADATA: + UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + + default: + setUiTranferDataByFieldName(dataTransfer, resource, fieldName); + } + } + + return dataTransfer; + } + + public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List<String> paramsToReturn) { + UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case SERVICE_API_ARTIFACTS: + if(service.getServiceApiArtifacts() == null) { + dataTransfer.setServiceApiArtifacts(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>()); + } else { + dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts()); + } + + break; + case FORWARDING_PATHS: + if(service.getForwardingPaths() == null) { + dataTransfer.setForwardingPaths(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>()); + } else { + dataTransfer.setForwardingPaths(service.getForwardingPaths()); + } + + break; + case METADATA: + UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + default: + setUiTranferDataByFieldName(dataTransfer, service, fieldName); + } + } + + return dataTransfer; + } + + + public static UiComponentMetadata convertToUiComponentMetadata(Component component) { + + UiComponentMetadata uiComponentMetadata = null; + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource)component; + uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + case SERVICE: + uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + default: + break; + } + return uiComponentMetadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java index 0cc415c80d..0aa8d5afa6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java @@ -27,39 +27,34 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; public class AuditHandler { - ComponentsUtils componentsUtils; - String instanceID; - private RegistrationRequest registrationRequest; + ComponentsUtils componentsUtils; + String instanceID; + private RegistrationRequest registrationRequest; - public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { - super(); - this.componentsUtils = componentsUtils; - this.instanceID = instanceID; - this.registrationRequest = registrationRequest; - } + public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { + super(); + this.componentsUtils = componentsUtils; + this.instanceID = instanceID; + this.registrationRequest = registrationRequest; + } - public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); - } + public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - } + public void auditRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - public void auditRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } - } - - public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - } + public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java index ae1de21ea8..2c2adaa970 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java @@ -20,224 +20,275 @@ package org.openecomp.sdc.be.distribution; -import java.util.List; - -import javax.annotation.Resource; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; -import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; -import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.components.distribution.engine.*; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; -import org.openecomp.sdc.be.distribution.api.client.ServerListResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.be.distribution.api.client.*; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Resource; +import javax.ws.rs.core.Response; +import java.util.List; -import fj.data.Either; +import static org.apache.commons.lang.BooleanUtils.isTrue; +import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName; +import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager; @Component("distributionBusinessLogic") public class DistributionBusinessLogic { - public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; - public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static Logger log = LoggerFactory.getLogger(DistributionBusinessLogic.class.getName()); - @Resource - private DistributionEngine distributionEngine; - - private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); - private CambriaHandler cambriaHandler; - - public Either<ServerListResponse, ResponseFormat> getUebServerList() { - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - List<String> serverList = distributionEngineConfiguration.getUebServers(); - - if (serverList != null && !serverList.isEmpty()) { - - ServerListResponse serverListResponse = new ServerListResponse(); - - serverListResponse.setUebServerList(serverList); - - return Either.left(serverListResponse); - } else { - ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(errorResponseWrapper); - } - - } - - public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) { - CambriaErrorResponse registerResponse = null; - try { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER); - - if (responseWrapper.isEmpty()) { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER); - // Second Register failed - unregister the first - if (!responseWrapper.isEmpty()) { - CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER); - } - } - - if (responseWrapper.isEmpty()) { - TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - } finally { - auditHandler.auditRegisterRequest(registerResponse); - } - } - - public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) { - Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>(); - try { - CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); - - CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); - - // Success unregister both topics - TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), getStatusTopicName(unRegistrationRequest.getDistrEnvName()), - unregisterClientConsumerTopicResponse.getOperationStatus(), unregisterClientProducerTopicResponse.getOperationStatus()); - - if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - - } finally { - auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); - } - } - - private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, CambriaErrorResponse currentResponse) { - if (cambriaResponseWrapper.isEmpty()) { - cambriaResponseWrapper.setInnerElement(currentResponse); - } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { - cambriaResponseWrapper.setInnerElement(currentResponse); - - } - - } - - public static String getNotificationTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); - - } - - public static String getStatusTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); - - } - - protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName; - if (subscriberType == SubscriberTypeEnum.PRODUCER) { - topicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); - } else { - topicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); - - } - log.debug("unregistering client as {} , from topic: {}", subscriberType.name(), topicName); - return getCambriaHandler().unRegisterFromTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType); - } - - private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - - TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); - topicResponse.setDistrNotificationTopicName(notificationTopicName); - topicResponse.setDistrStatusTopicName(statusTopicName); - return topicResponse; - } - - protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName, errorMsg; - - // Register for notifications as consumer - if (subscriberType == SubscriberTypeEnum.CONSUMER) { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; - } - // Register for status as producer - else { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; - } - log.debug("registering client as {} , from topic: {}", subscriberType.name(), topicName); - CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), subscriberType); - - if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { - Response failedRegistrationResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - responseWrapper.setInnerElement(failedRegistrationResponse); - } - return registerToTopic; - } - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; - } - - public ResponseFormatManager getResponseFormatManager() { - return responseFormatManager; - } - - public DistributionEngine getDistributionEngine() { - return distributionEngine; - } - - public CambriaHandler getCambriaHandler() { - if (cambriaHandler == null) { - cambriaHandler = new CambriaHandler(); - } - return cambriaHandler; - } + public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; + public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger LOGGER = LoggerFactory.getLogger(DistributionBusinessLogic.class); + @Resource + private IDistributionEngine distributionEngine; + + private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); + private CambriaHandler cambriaHandler; + + private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) { + if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){ + registrationRequest.setDistEnvEndPoints(config.getUebServers()); + } + } + public Either<ServerListResponse, ResponseFormat> getUebServerList() { + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + + List<String> serverList = distributionEngineConfiguration.getUebServers(); + + if (serverList != null && !serverList.isEmpty()) { + + ServerListResponse serverListResponse = new ServerListResponse(); + + serverListResponse.setUebServerList(serverList); + + return Either.left(serverListResponse); + } else { + ResponseFormat errorResponseWrapper = getResponseFormatManager() + .getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponseWrapper); + } + + } + + public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, + AuditHandler auditHandler) { + CambriaErrorResponse registerResponse = null; + try { + DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration(); + String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty(); + + // Story [347698] Distribution Client Get Indication from + // component whether to register as consumer and producer on + // status topic + boolean registeredAsConsumerOnStatus = false; + if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) { + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + registeredAsConsumerOnStatus = responseWrapper.isEmpty(); + + } + + if (responseWrapper.isEmpty()) { + String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, notificationTopicName); + } + // Unregister Rollback + if (!responseWrapper.isEmpty()) { + if (isRegisteredAsProducerOnStatusSuccess) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + } + if (registeredAsConsumerOnStatus) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + } + } + + if (responseWrapper.isEmpty()) { + TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + } + + } catch (Exception e) { + LOGGER.error("registration to topic failed", e); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + "registration of subscriber to topic"); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + } finally { + auditHandler.auditRegisterRequest(registerResponse); + } + } + + public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, + AuditHandler auditHandler) { + Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>(); + try { + String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER, + statusTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); + + String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER, + notificationTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); + + // Success unregister both topics + TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse( + getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), + getStatusTopicName(unRegistrationRequest.getDistrEnvName()), + unregisterClientConsumerTopicResponse.getOperationStatus(), + unregisterClientProducerTopicResponse.getOperationStatus()); + + if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, + "unregistration failed"); + responseWrapper.setInnerElement( + Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); + } + } catch (Exception e) { + LOGGER.error("unregistered to topic failed", e); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + + } finally { + auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); + } + } + + private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, + CambriaErrorResponse currentResponse) { + if (cambriaResponseWrapper.isEmpty()) { + cambriaResponseWrapper.setInnerElement(currentResponse); + } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { + cambriaResponseWrapper.setInnerElement(currentResponse); + + } + + } + + public static String getNotificationTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); + + } + + public static String getStatusTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); + + } + + protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, + SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(unRegistrationRequest, config); + + LOGGER.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints()); + return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(), + config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName); + } + + private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + + TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); + topicResponse.setDistrNotificationTopicName(notificationTopicName); + topicResponse.setDistrStatusTopicName(statusTopicName); + return topicResponse; + } + + protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, + RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(registrationRequest, config); + String errorMsg; + + // Register for notifications as consumer + if (subscriberType == SubscriberTypeEnum.CONSUMER) { + errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; + } + // Register for status as producer + else { + errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; + } + LOGGER.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints()); + CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + subscriberType, topicName); + + if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { + Response failedRegistrationResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + errorMsg); + responseWrapper.setInnerElement(failedRegistrationResponse); + } + return registerToTopic; + } + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { + return Response.status(requestErrorWrapper.getStatus()) + .entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + } + + public ResponseFormatManager getResponseFormatManager() { + return responseFormatManager; + } + + public IDistributionEngine getDistributionEngine() { + return distributionEngine; + } + + public CambriaHandler getCambriaHandler() { + if (cambriaHandler == null) { + cambriaHandler = new CambriaHandler(); + } + return cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java index a6a6602cb0..3edb3d8f69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java @@ -21,5 +21,5 @@ package org.openecomp.sdc.be.distribution.api.client; public enum CambriaOperationStatus { - OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, + OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java index ef14efe4f8..1dfbdb538d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java @@ -20,21 +20,43 @@ package org.openecomp.sdc.be.distribution.api.client; +import java.util.List; + public class RegistrationRequest { - String apiPublicKey; - String distrEnvName; + String apiPublicKey; + String distrEnvName; + Boolean isConsumerToSdcDistrStatusTopic; + List<String> distEnvEndPoints; + + public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic) { + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + public RegistrationRequest(String apiPublicKey, String distrEnvName, List<String> distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){ + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.distEnvEndPoints = distEnvEndPoints; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + + public String getApiPublicKey() { + return apiPublicKey; + } - public RegistrationRequest(String apiPublicKey, String distrEnvName) { - this.apiPublicKey = apiPublicKey; - this.distrEnvName = distrEnvName; - } + public String getDistrEnvName() { + return distrEnvName; + } - public String getApiPublicKey() { - return apiPublicKey; - } + public Boolean getIsConsumerToSdcDistrStatusTopic() { + return isConsumerToSdcDistrStatusTopic; + } + public List<String> getDistEnvEndPoints() { + return distEnvEndPoints; + } - public String getDistrEnvName() { - return distrEnvName; - } + public void setDistEnvEndPoints(List<String> distEnvEndPoints) { + this.distEnvEndPoints = distEnvEndPoints; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java index 267a691e29..2eebedfd7c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java @@ -24,13 +24,13 @@ import java.util.List; public class ServerListResponse { - private List<String> uebServerList; + private List<String> uebServerList; - public List<String> getUebServerList() { - return uebServerList; - } + public List<String> getUebServerList() { + return uebServerList; + } - public void setUebServerList(List<String> uebServerList) { - this.uebServerList = uebServerList; - } + public void setUebServerList(List<String> uebServerList) { + this.uebServerList = uebServerList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java index e2a34a19d5..5d1b0657c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java @@ -21,22 +21,22 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicRegistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; + String distrNotificationTopicName; + String distrStatusTopicName; - public void setDistrNotificationTopicName(String distrNotificationTopicName) { - this.distrNotificationTopicName = distrNotificationTopicName; - } + public void setDistrNotificationTopicName(String distrNotificationTopicName) { + this.distrNotificationTopicName = distrNotificationTopicName; + } - public void setDistrStatusTopicName(String distrStatusTopicName) { - this.distrStatusTopicName = distrStatusTopicName; - } + public void setDistrStatusTopicName(String distrStatusTopicName) { + this.distrStatusTopicName = distrStatusTopicName; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java index ffb9f9352f..621cd37a54 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java @@ -21,32 +21,32 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicUnregistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; - CambriaOperationStatus notificationUnregisterResult; - CambriaOperationStatus statusUnregisterResult; + String distrNotificationTopicName; + String distrStatusTopicName; + CambriaOperationStatus notificationUnregisterResult; + CambriaOperationStatus statusUnregisterResult; - public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { - super(); - this.distrNotificationTopicName = distrNotificationTopicName; - this.distrStatusTopicName = distrStatusTopicName; - this.notificationUnregisterResult = notificationUnregisterResult; - this.statusUnregisterResult = statusUnregisterResult; - } + public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { + super(); + this.distrNotificationTopicName = distrNotificationTopicName; + this.distrStatusTopicName = distrStatusTopicName; + this.notificationUnregisterResult = notificationUnregisterResult; + this.statusUnregisterResult = statusUnregisterResult; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } - public CambriaOperationStatus getNotificationUnregisterResult() { - return notificationUnregisterResult; - } + public CambriaOperationStatus getNotificationUnregisterResult() { + return notificationUnregisterResult; + } - public CambriaOperationStatus getStatusUnregisterResult() { - return statusUnregisterResult; - } + public CambriaOperationStatus getStatusUnregisterResult() { + return statusUnregisterResult; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java index 125c1012b2..984a831c8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java @@ -20,45 +20,33 @@ package org.openecomp.sdc.be.distribution.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; import org.openecomp.sdc.be.servlets.BeGenericServlet; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; /** * This Servlet serves external users to download artifacts. @@ -73,249 +61,233 @@ import io.swagger.annotations.ApiResponses; @Singleton public class DistributionCatalogServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - @Context - private HttpServletRequest request; + private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class); + @Context + private HttpServletRequest request; + + // ******************************************************* + // Download (GET) artifacts + // **********************************************************/ + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadServiceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("artifactName") final String artifactName) { + + Response response = null; + String requestURI = request.getRequestURI(); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); - // ******************************************************* - // Download (GET) artifacts - // **********************************************************/ - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadServiceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceName + * @param resourceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadResourceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceName") final String resourceName, + @PathParam("resourceVersion") final String resourceVersion, + @PathParam("artifactName") final String artifactName) { - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + Response response = null; + String requestURI = request.getRequestURI(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download Murano package artifact for service - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceName - * @param resourceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadResourceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceName") final String resourceName, - @PathParam("resourceVersion") final String resourceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceInstanceName + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadResourceInstanceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceInstanceName") final String resourceInstanceName, + @PathParam("artifactName") final String artifactName) { - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceInstanceName - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(nickname = "downloadResourceInstanceArtifactByName",value = "Download resource instance artifact by artifact name", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadResourceInstanceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceInstanceName") final String resourceInstanceName, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Response response = null; + String requestURI = request.getRequestURI(); - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java index 6add877fe0..b5c322f90b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java @@ -20,20 +20,9 @@ package org.openecomp.sdc.be.distribution.servlet; -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.distribution.AuditHandler; @@ -56,17 +45,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.ResponseHeader; +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * This Servlet serves external users for distribution purposes. @@ -81,321 +67,315 @@ import io.swagger.annotations.ResponseHeader; @Singleton public class DistributionServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionServlet.class.getName()); - @Resource - private DistributionBusinessLogic distributionLogic; - @Context - private HttpServletRequest request; - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param authorization - * @return - */ - @GET - @Path("/distributionUebCluster") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", - //TODO Tal G fix response headers - responseHeaders = { - @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), - @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getUebServerList( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - if (instanceId == null) { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - response = buildErrorResponse(responseFormat); - getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - } - - try { - Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList(); - - if (actionResponse.isRight()) { - responseFormat = actionResponse.right().value(); - response = buildErrorResponse(responseFormat); - } else { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - } - - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "failed to get ueb serbver list from cofiguration"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); - log.debug("failed to get ueb serbver list from cofiguration", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - response = buildErrorResponse(responseFormat); - return response; - } - - } - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/registerForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - //TODO Tal G fix response headers and to check missing header validations with Michael L - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response registerForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, registrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - - if (responseWrapper.isEmpty()) { - distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - /** - * Returns list of valid artifact types for validation done in the distribution client.<br> - * The list is the representation of the values of the enum ArtifactTypeEnum. - * - * @param requestId - * @param instanceId - * @param authorization - * @param accept - * @return - */ - @GET - @Path("/artifactTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - public Response getValidArtifactTypes( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - - Wrapper<Response> responseWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); - if (responseWrapper.isEmpty()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); - } else { - response = responseWrapper.getInnerElement(); - } - return response; - } - - /** - * Removes from subscription for distribution notifications - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/unRegisterForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") - //TODO Edit the responses - @ApiResponses(value = { - @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response unRegisterForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - if (responseWrapper.isEmpty()) { - distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) { - - // DE194021 - StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); - // DE194021 - // StorageOperationStatus environmentStatus = - // distributionLogic.getDistributionEngine().isEnvironmentAvailable(distrEnvName); - if (environmentStatus != StorageOperationStatus.OK) { - if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); - responseWrapper.setInnerElement(missingHeaderResponse); - } else { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(missingHeaderResponse); - } - } - - } - - private void init(HttpServletRequest request) { - if (distributionLogic == null) { - distributionLogic = getDistributionBL(request.getSession().getServletContext()); - } - } - - private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { - if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); - responseWrapper.setInnerElement(missingHeaderResponse); - // Audit - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - - } - - } - - private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) { - if (requestJson == null || requestJson.isEmpty()) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); - if (eitherRegistration.isLeft()) { - RegistrationRequest registrationRequest = eitherRegistration.left().value(); - if (registrationRequest.getApiPublicKey() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); - responseWrapper.setInnerElement(missingBodyResponse); - - } else if (registrationRequest.getDistrEnvName() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - registrationRequestWrapper.setInnerElement(registrationRequest); - } - } else { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } - } - - } - - private DistributionBusinessLogic getDistributionBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(DistributionBusinessLogic.class); - } - - private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { - return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); - } + private static final Logger log = LoggerFactory.getLogger(DistributionServlet.class); + @Resource + private DistributionBusinessLogic distributionLogic; + @Context + private HttpServletRequest request; + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param authorization + * @return + */ + @GET + @Path("/distributionUebCluster") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", + //TODO Tal G fix response headers + responseHeaders = { + @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), + @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getUebServerList( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + if (instanceId == null) { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + response = buildErrorResponse(responseFormat); + getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + } + + try { + Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList(); + + if (actionResponse.isRight()) { + responseFormat = actionResponse.right().value(); + response = buildErrorResponse(responseFormat); + } else { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + } + + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); + log.debug("failed to get ueb serbver list from cofiguration", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + response = buildErrorResponse(responseFormat); + return response; + } + + } + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/registerForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + //TODO Tal G fix response headers and to check missing header validations with Michael L + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response registerForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, registrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + + if (responseWrapper.isEmpty()) { + distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + /** + * Returns list of valid artifact types for validation done in the distribution client.<br> + * The list is the representation of the values of the enum ArtifactTypeEnum. + * + * @param requestId + * @param instanceId + * @param authorization + * @param accept + * @return + */ + @GET + @Path("/artifactTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + public Response getValidArtifactTypes( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + + Wrapper<Response> responseWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); + if (responseWrapper.isEmpty()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); + } else { + response = responseWrapper.getInnerElement(); + } + return response; + } + + /** + * Removes from subscription for distribution notifications + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/unRegisterForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") + //TODO Edit the responses + @ApiResponses(value = { + @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response unRegisterForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + if (responseWrapper.isEmpty()) { + distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) { + + // DE194021 + StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); + if (environmentStatus != StorageOperationStatus.OK) { + if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); + responseWrapper.setInnerElement(missingHeaderResponse); + } else { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(missingHeaderResponse); + } + } + + } + + private void init(HttpServletRequest request) { + if (distributionLogic == null) { + distributionLogic = getDistributionBL(request.getSession().getServletContext()); + } + } + + private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { + if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); + responseWrapper.setInnerElement(missingHeaderResponse); + // Audit + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + + } + + } + + private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) { + if (requestJson == null || requestJson.isEmpty()) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); + if (eitherRegistration.isLeft()) { + RegistrationRequest registrationRequest = eitherRegistration.left().value(); + if (registrationRequest.getApiPublicKey() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); + responseWrapper.setInnerElement(missingBodyResponse); + + } else if (registrationRequest.getDistrEnvName() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + registrationRequestWrapper.setInnerElement(registrationRequest); + } + } else { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } + } + + } + + private DistributionBusinessLogic getDistributionBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(DistributionBusinessLogic.class); + } + + private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { + return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java new file mode 100644 index 0000000000..28621bcb41 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.dto; + +/** + * Created by yavivi on 18/02/2018. + */ +public class ExternalRefDTO { + private String referenceUUID; + + public ExternalRefDTO(){ + //Empty constructor for serialization purposes + } + + public ExternalRefDTO(String ref){ + this.referenceUUID = ref; + } + + public String getReferenceUUID() { + return referenceUUID; + } + + public void setReferenceUUID(String referenceUUID) { + this.referenceUUID = referenceUUID; + } + + @Override + public String toString() { + return this.referenceUUID; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java index c88ec87d58..6ffa3a7c34 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.ecomp; -import java.util.LinkedList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - +import fj.data.Either; import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; import org.openecomp.portalsdk.core.restful.domain.EcompRole; @@ -44,343 +40,342 @@ import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import java.util.LinkedList; +import java.util.List; + -/* - * PortalAPIException(String message, Throwable cause); - */ public class EcompIntImpl implements IPortalRestAPIService { - private static Logger log = LoggerFactory.getLogger(EcompIntImpl.class.getName()); - - public EcompIntImpl() { - log.debug("EcompIntImpl Class Instantiated"); - } - - @Override - public void pushUser(EcompUser user) throws PortalAPIException { - log.debug("Start handle request of ECOMP pushUser"); - try { - if (user == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO); - log.debug("Recieved null for argument user"); - throw new PortalAPIException("Recieved null for argument user"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - final String modifierAttId = "jh0003"; - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - Either<User, String> newASDCUser = EcompUserConverter.convertEcompUserToUser(user); - if (newASDCUser.isRight()) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO); - log.debug("Failed to create user {}", user.toString()); - throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); - } else if (newASDCUser.left().value() == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); - log.debug("Failed to create user {}", user.toString()); - throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); - } - - User convertedAsdcUser = newASDCUser.left().value(); - Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser); - - // ALREADY EXIST ResponseFormat - final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006"; - - if (createUserResponse.isRight()) { - if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) { - log.debug("Failed to create user {}", user.toString()); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to create user" + createUserResponse.right()); - } - log.debug("User already exist {}", user.toString()); - } - log.debug("User created {}", user.toString()); - } catch (Exception e) { - log.debug("Failed to create user {}", user, e); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to create user", e); - } - } - - /* - * (non-Javadoc) - * - * - * loginId - equals to userId - * - */ - @Override - public void editUser(String loginId, EcompUser user) throws PortalAPIException { - log.debug("Start handle request of ECOMP editUser"); - - try { - if (user == null) { - log.debug("Recieved null for argument user"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument user"); - } else if (loginId == null) { - log.debug("Recieved null for argument loginId"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument loginId"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { - log.debug("loginId and user loginId not equal"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO); - throw new PortalAPIException("loginId not equals to the user loginId field"); - } else if (user.getLoginId() == null) { - user.setLoginId(loginId); - } - - Either<User, String> asdcUser = EcompUserConverter.convertEcompUserToUser(user); - if (asdcUser.isRight()) { - log.debug("Failed to convert user"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO); - throw new PortalAPIException(asdcUser.right().value()); - } else if (asdcUser.left().value() == null) { - log.debug("NULL pointer returned from user converter"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to edit user"); - } - - Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value()); - - if (updateUserCredentialsResponse.isRight()) { - log.debug("Failed to updateUserCredentials"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value()); - } - } catch (Exception e) { - log.debug("Failed to updateUserCredentials"); - throw new PortalAPIException("Failed to edit user", e); - } - - } - - @Override - public EcompUser getUser(String loginId) throws PortalAPIException { - log.debug("Start handle request of ECOMP getUser"); - - try { - - if (loginId == null) { - log.debug("Recieved null for argument loginId"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument loginId"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false); - - if (getUserResponse.isRight()) { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get User" + getUserResponse.right()); - } else { - if (getUserResponse.left().value() != null) { - Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); - if (ecompUser.isLeft() && ecompUser.left().value() != null) { - return ecompUser.left().value(); - } else { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException(ecompUser.right().value()); - } - } else { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get User" + getUserResponse.right()); - } - } - } catch (Exception e) { - log.debug("Failed to get User"); - throw new PortalAPIException("Failed to get User", e); - } - } - - @Override - public List<EcompUser> getUsers() throws PortalAPIException { - log.debug("Start handle request of ECOMP getUsers"); - - try { - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - final String modifierAttId = "jh0003"; - - Either<List<User>, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null); - - if (getUsersResponse.isRight()) { - log.debug("Failed to get Users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); - } else { - if (getUsersResponse.left().value() != null) { - List<EcompUser> ecompUserList = new LinkedList<>(); - for (User user : getUsersResponse.left().value()) { - Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(user); - if (ecompUser.isRight()) { - log.debug("Failed to convert User {}", user); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); - continue; - } else if (ecompUser.left().value() == null) { - log.debug("Failed to convert User {}", user); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); - continue; - } - ecompUserList.add(ecompUser.left().value()); - } - return ecompUserList; - } else { - log.debug("Failed to get users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); - } - } - } catch (Exception e) { - log.debug("Failed to get users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users", e); - } - } - - @Override - public List<EcompRole> getAvailableRoles() throws PortalAPIException { - log.debug("Start handle request of ECOMP getAvailableRoles"); - try { - List<EcompRole> ecompRolesList = new LinkedList<>(); - for (Role role : Role.values()) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(new Long(role.ordinal())); - ecompRole.setName(role.name()); - ecompRolesList.add(ecompRole); - } - - if (ecompRolesList.isEmpty()) { - throw new PortalAPIException(); - } - - return ecompRolesList; - } catch (Exception e) { - log.debug("Failed to fetch roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO); - throw new PortalAPIException("Roles fetching failed", e); - } - - } - - /** - * The user role updated through this method only - */ - @Override - public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException { - log.debug("Start handle request of ECOMP pushUserRole"); - - final String modifierAttId = "jh0003"; - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - String updatedRole = null; - - if (roles == null) { - throw new PortalAPIException("Error: Recieved null for roles"); - } else if (roles.iterator().hasNext()) { - EcompRole ecompRole = roles.iterator().next(); - updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole); - log.debug("pushing role: {} to user: {}", updatedRole, loginId); - Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); - if (updateUserRoleResponse.isRight()) { - log.debug("Error: Failed to update role"); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); - } - } else { - log.debug("Error: No roles in List"); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO); - //throw new PortalAPIException("Error: No roles in List"); - //in this cases we want to deactivate the user - Either<User, ResponseFormat> deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId); - if (deActivateUserResponse.isRight()) { - log.debug("Error: Failed to deactivate user {}",loginId); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO); - throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage()); - } - } - } - - @Override - public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException { - try { - log.debug("Start handle request of ECOMP getUserRoles"); - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false); - - if (getUserResponse.isRight()) { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); - } else { - if (getUserResponse.left().value() != null) { - Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); - if (ecompUser.isRight()) { - log.debug("Error: Failed to convert Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); - throw new PortalAPIException(ecompUser.right().value()); - } else if (ecompUser.left().value() == null) { - log.debug("Error: Failed to convert Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); - throw new PortalAPIException(); - } - - return new LinkedList<>(ecompUser.left().value().getRoles()); - } else { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); - } - } - } catch (Exception e) { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Roles", e); - } - } - - @Override - public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { - // TODO Validation should be changed completely - final String USERNAME = request.getHeader("username"); - final String PASSWORD = request.getHeader("password"); - - if (USERNAME != null && PASSWORD != null) { - if (!USERNAME.equals("") && !PASSWORD.equals("")) { - log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD); - return true; - } - } - - log.debug("User authentication failed"); - return false; - } - - private UserBusinessLogic getUserBusinessLogic() { - ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); - UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); - return userBusinessLogic; - } - - /** + private static final Logger log = LoggerFactory.getLogger(EcompIntImpl.class); + + public EcompIntImpl() { + log.debug("EcompIntImpl Class Instantiated"); + } + + @Override + public void pushUser(EcompUser user) throws PortalAPIException { + log.debug("Start handle request of ECOMP pushUser"); + try { + if (user == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO); + log.debug("Recieved null for argument user"); + throw new PortalAPIException("Recieved null for argument user"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + final String modifierAttId = "jh0003"; + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + Either<User, String> newASDCUser = EcompUserConverter.convertEcompUserToUser(user); + if (newASDCUser.isRight()) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO); + log.debug("Failed to create user {}", user); + throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); + } else if (newASDCUser.left().value() == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); + log.debug("Failed to create user {}", user); + throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); + } + + User convertedAsdcUser = newASDCUser.left().value(); + Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser); + + // ALREADY EXIST ResponseFormat + final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006"; + + if (createUserResponse.isRight()) { + if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) { + log.debug("Failed to create user {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to create user" + createUserResponse.right()); + } + log.debug("User already exist {}", user); + } + log.debug("User created {}", user); + } catch (Exception e) { + log.debug("Failed to create user {}", user, e); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to create user", e); + } + } + + /* + * (non-Javadoc) + * + * + * loginId - equals to userId + * + */ + @Override + public void editUser(String loginId, EcompUser user) throws PortalAPIException { + log.debug("Start handle request of ECOMP editUser"); + + try { + if (user == null) { + log.debug("Recieved null for argument user"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument user"); + } else if (loginId == null) { + log.debug("Recieved null for argument loginId"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument loginId"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { + log.debug("loginId and user loginId not equal"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO); + throw new PortalAPIException("loginId not equals to the user loginId field"); + } else if (user.getLoginId() == null) { + user.setLoginId(loginId); + } + + Either<User, String> asdcUser = EcompUserConverter.convertEcompUserToUser(user); + if (asdcUser.isRight()) { + log.debug("Failed to convert user"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO); + throw new PortalAPIException(asdcUser.right().value()); + } else if (asdcUser.left().value() == null) { + log.debug("NULL pointer returned from user converter"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to edit user"); + } + + Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value()); + + if (updateUserCredentialsResponse.isRight()) { + log.debug("Failed to updateUserCredentials"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value()); + } + } catch (Exception e) { + log.debug("Failed to updateUserCredentials"); + throw new PortalAPIException("Failed to edit user", e); + } + + } + + @Override + public EcompUser getUser(String loginId) throws PortalAPIException { + log.debug("Start handle request of ECOMP getUser"); + + try { + + if (loginId == null) { + log.debug("Recieved null for argument loginId"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument loginId"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false); + + if (getUserResponse.isRight()) { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get User" + getUserResponse.right()); + } else { + if (getUserResponse.left().value() != null) { + Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); + if (ecompUser.isLeft() && ecompUser.left().value() != null) { + return ecompUser.left().value(); + } else { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException(ecompUser.right().value()); + } + } else { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get User" + getUserResponse.right()); + } + } + } catch (Exception e) { + log.debug("Failed to get User"); + throw new PortalAPIException("Failed to get User", e); + } + } + + @Override + public List<EcompUser> getUsers() throws PortalAPIException { + log.debug("Start handle request of ECOMP getUsers"); + + try { + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + final String modifierAttId = "jh0003"; + + Either<List<User>, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null); + + if (getUsersResponse.isRight()) { + log.debug("Failed to get Users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); + } else { + if (getUsersResponse.left().value() != null) { + List<EcompUser> ecompUserList = new LinkedList<>(); + for (User user : getUsersResponse.left().value()) { + Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(user); + if (ecompUser.isRight()) { + log.debug("Failed to convert User {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); + continue; + } else if (ecompUser.left().value() == null) { + log.debug("Failed to convert User {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); + continue; + } + ecompUserList.add(ecompUser.left().value()); + } + return ecompUserList; + } else { + log.debug("Failed to get users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); + } + } + } catch (Exception e) { + log.debug("Failed to get users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users", e); + } + } + + @Override + public List<EcompRole> getAvailableRoles() throws PortalAPIException { + log.debug("Start handle request of ECOMP getAvailableRoles"); + try { + List<EcompRole> ecompRolesList = new LinkedList<>(); + for (Role role : Role.values()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(new Long(role.ordinal())); + ecompRole.setName(role.name()); + ecompRolesList.add(ecompRole); + } + + if (ecompRolesList.isEmpty()) { + throw new PortalAPIException(); + } + + return ecompRolesList; + } catch (Exception e) { + log.debug("Failed to fetch roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO); + throw new PortalAPIException("Roles fetching failed", e); + } + + } + + /** + * The user role updated through this method only + */ + @Override + public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException { + log.debug("Start handle request of ECOMP pushUserRole"); + + final String modifierAttId = "jh0003"; + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + String updatedRole = null; + + if (roles == null) { + throw new PortalAPIException("Error: Recieved null for roles"); + } else if (roles.iterator().hasNext()) { + EcompRole ecompRole = roles.iterator().next(); + updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole); + log.debug("pushing role: {} to user: {}", updatedRole, loginId); + Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); + if (updateUserRoleResponse.isRight()) { + log.debug("Error: Failed to update role"); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); + } + } else { + log.debug("Error: No roles in List"); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO); + //in this cases we want to deactivate the user + Either<User, ResponseFormat> deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId); + if (deActivateUserResponse.isRight()) { + log.debug("Error: Failed to deactivate user {}",loginId); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO); + throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage()); + } + } + } + + @Override + public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException { + try { + log.debug("Start handle request of ECOMP getUserRoles"); + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false); + + if (getUserResponse.isRight()) { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); + } else { + if (getUserResponse.left().value() != null) { + Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); + if (ecompUser.isRight()) { + log.debug("Error: Failed to convert Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); + throw new PortalAPIException(ecompUser.right().value()); + } else if (ecompUser.left().value() == null) { + log.debug("Error: Failed to convert Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); + throw new PortalAPIException(); + } + + return new LinkedList<>(ecompUser.left().value().getRoles()); + } else { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); + } + } + } catch (Exception e) { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Roles", e); + } + } + + @Override + public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { + // TODO Validation should be changed completely + final String USERNAME = request.getHeader("username"); + final String PASSWORD = request.getHeader("password"); + + if (USERNAME != null && PASSWORD != null) { + if (!USERNAME.equals("") && !PASSWORD.equals("")) { + log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD); + return true; + } + } + + log.debug("User authentication failed"); + return false; + } + + private UserBusinessLogic getUserBusinessLogic() { + ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); + UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); + return userBusinessLogic; + } + + /** * Gets and returns the userId for the logged-in user based on the request. * If any error occurs, the method should throw PortalApiException with an * appropriate message. The FW library will catch the exception and send an @@ -399,8 +394,8 @@ public class EcompIntImpl implements IPortalRestAPIService { * @throws PortalAPIException * If an unexpected error occurs while processing the request. */ - @Override - public String getUserId(HttpServletRequest request) throws PortalAPIException { - return request.getHeader(Constants.USER_ID_HEADER); - } + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + return request.getHeader(Constants.USER_ID_HEADER); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java index 93de8fed2c..b02a4a52cd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java @@ -20,30 +20,15 @@ package org.openecomp.sdc.be.ecomp.converters; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; -import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.*; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -52,341 +37,339 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.*; @org.springframework.stereotype.Component("asset-metadata-utils") public class AssetMetadataConverter { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - - @Autowired - private ComponentsUtils componentsUtils; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - /* - * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() - */ - public Either<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL, boolean detailed) { - if (componentList == null || componentList.isEmpty()) { - return Either.left(new LinkedList<>()); - } - List<AssetMetadata> retResList = new LinkedList<>(); - - for (Component curr : componentList) { - Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - retResList.add(resMetaData.left().value()); - } - - return Either.left(retResList); - - } - - public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { - ComponentTypeEnum componentType = component.getComponentType(); - Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); - - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - else{ - return Either.left(resMetaData.left().value()); - } - - } - - private Either<? extends AssetMetadata, ResponseFormat> convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { - - switch (componentType) { - - case RESOURCE: - - return generateResourceMeatdata(serverBaseURL, detailed, curr); - - case SERVICE: - - return generateServiceMetadata(serverBaseURL, detailed, curr); - - // For future US's that include product - /* - * case PRODUCT: if (component instanceof Product) { List<ProductAssetMetadata> retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return - * Either.left(retResList); - */ - default: - - ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); - return Either.right(responseFormat); - } - } - - private Either<? extends AssetMetadata, ResponseFormat> generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData; - metaData = createMetadaObject(detailed, curr.getComponentType()); - metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); - - if (detailed) { - Either<ResourceAssetDetailedMetadata, StorageOperationStatus> converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { - AssetMetadata metaData = null; - switch (type) { - case SERVICE: - if (!detailed) { - metaData = new ServiceAssetMetadata(); - } else { - metaData = new ServiceAssetDetailedMetadata(); - } - break; - case RESOURCE: - if (!detailed) { - metaData = new ResourceAssetMetadata(); - } else { - metaData = new ResourceAssetDetailedMetadata(); - } - break; - default: - break; - } - return metaData; - } - - private Either<? extends AssetMetadata, ResponseFormat> generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); - - metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); - - if (detailed) { - Either<ServiceAssetDetailedMetadata, StorageOperationStatus> converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private <U extends AssetMetadata, T extends Component> U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { - asset.setUuid(component.getUUID()); - asset.setInvariantUUID(component.getInvariantUUID()); - asset.setName(component.getName()); - asset.setVersion(component.getVersion()); - if (!detailed) { - asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); - } else { - String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); - asset.setToscaModelURL(toscaModelUrl); - } - - return asset; - } - - private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ - CategoryDefinition categoryDefinition = resource.getCategories().get(0); - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName()); - } - assetToPopulate.setResourceType(resource.getResourceType().name()); - assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); - - return (T) assetToPopulate; - } - - private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); - - if(service.getCategories() != null && !service.getCategories().isEmpty()){ - CategoryDefinition categoryDefinition = service.getCategories().get(0); - assetToPopulate.setCategory(categoryDefinition.getName()); - } - - assetToPopulate.setLifecycleState(service.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); - assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); - - return (T) assetToPopulate; - } - - private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { - - List<ComponentInstance> componentInstances = resource.getComponentInstances(); - - if (componentInstances != null) { - Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); - assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); - assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); - assetToPopulate.setDescription(resource.getDescription()); - return Either.left(assetToPopulate); - } - - private <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { - - List<ComponentInstance> componentInstances = service.getComponentInstances(); - - if (componentInstances != null) { - Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts(); - assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); - - return Either.left(assetToPopulate); - } - - private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map<String, ArtifactDefinition> artifacts) { - - List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(resource, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service, Map<String, ArtifactDefinition> artifacts) { - - List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(service, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) { - List<ArtifactMetadata> artifactMetaList = new LinkedList<>(); - if (artifacts != null) { - Collection<ArtifactDefinition> artefactDefList = artifacts.values(); - - for (ArtifactDefinition artifactDefinition : artefactDefList) { - if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { - ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); - artifactMetaList.add(convertedArtifactMetadata); - } - } - } - return artifactMetaList.isEmpty() ? null : artifactMetaList; - } - - private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { - // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} - final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; - - // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} - final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; - - ArtifactMetadata metadata = new ArtifactMetadata(); - - metadata.setArtifactName(artifact.getArtifactName()); - metadata.setArtifactType(artifact.getArtifactType()); - - if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { - metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); - } else { - metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); - } - - metadata.setArtifactDescription(artifact.getDescription()); - metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); - metadata.setArtifactChecksum(artifact.getArtifactChecksum()); - metadata.setArtifactUUID(artifact.getArtifactUUID()); - metadata.setArtifactVersion(artifact.getArtifactVersion()); - metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); - metadata.setArtifactLabel(artifact.getArtifactLabel()); - metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); - return metadata; - } - - private Either<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) { - List<ResourceInstanceMetadata> retList = new LinkedList<>(); - Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>(); - - for (ComponentInstance componentInstance : componentInstances) { - ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); - String componentUid = componentInstance.getComponentUid(); - String invariantUUID, resourceUUID; - - if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); - if (eitherResource.isRight()) { - log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); - return Either.right(eitherResource.right().value()); - } else { - final Resource resource = eitherResource.left().value(); - invariantUUID = resource.getInvariantUUID(); - resourceUUID = resource.getUUID(); - ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); - uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); - } - } else { - invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); - resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); - } - - metadata.setResourceInvariantUUID(invariantUUID); - metadata.setResourceUUID(resourceUUID); - metadata.setResourceInstanceName(componentInstance.getName()); - metadata.setResourceName(componentInstance.getComponentName()); - metadata.setResourceVersion(componentInstance.getComponentVersion()); - metadata.setResoucreType(componentInstance.getOriginType().getValue()); - - if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ - LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>(); - Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values(); - for (ArtifactDefinition artifactDefinition : values) { - ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); - artifactMetaList.add(converted); - } - metadata.setArtifacts(artifactMetaList); - } - retList.add(metadata); - } - return Either.left(retList); - } - - // For future US to support Product - /* - * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); - * - * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); - * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); - * - * List<CategoryDefinition> categories = product.getCategories(); List<ProductCategoryGroupMetadata> categoryMetadataList = new LinkedList<>(); - * - * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List<SubCategoryDefinition> subcategories = - * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List<GroupDefinition> groups = product.getGroups(); for (GroupDefinition - * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); - * return retProdAsset; } } - */ + private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + /* + * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() + */ + public Either<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL, boolean detailed) { + if (componentList == null || componentList.isEmpty()) { + return Either.left(new LinkedList<>()); + } + List<AssetMetadata> retResList = new LinkedList<>(); + + for (Component curr : componentList) { + Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + retResList.add(resMetaData.left().value()); + } + + return Either.left(retResList); + + } + + public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + ComponentTypeEnum componentType = component.getComponentType(); + Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); + + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + else{ + return Either.left(resMetaData.left().value()); + } + + } + + private Either<? extends AssetMetadata, ResponseFormat> convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { + + switch (componentType) { + + case RESOURCE: + + return generateResourceMeatdata(serverBaseURL, detailed, curr); + + case SERVICE: + + return generateServiceMetadata(serverBaseURL, detailed, curr); + + // For future US's that include product + /* + * case PRODUCT: if (component instanceof Product) { List<ProductAssetMetadata> retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return + * Either.left(retResList); + */ + default: + + ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); + return Either.right(responseFormat); + } + } + + private Either<? extends AssetMetadata, ResponseFormat> generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData; + metaData = createMetadaObject(detailed, curr.getComponentType()); + metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); + + if (detailed) { + Either<ResourceAssetDetailedMetadata, StorageOperationStatus> converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { + AssetMetadata metaData = null; + switch (type) { + case SERVICE: + if (!detailed) { + metaData = new ServiceAssetMetadata(); + } else { + metaData = new ServiceAssetDetailedMetadata(); + } + break; + case RESOURCE: + if (!detailed) { + metaData = new ResourceAssetMetadata(); + } else { + metaData = new ResourceAssetDetailedMetadata(); + } + break; + default: + break; + } + return metaData; + } + + private Either<? extends AssetMetadata, ResponseFormat> generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); + + metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); + + if (detailed) { + Either<ServiceAssetDetailedMetadata, StorageOperationStatus> converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private <U extends AssetMetadata, T extends Component> U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { + asset.setUuid(component.getUUID()); + asset.setInvariantUUID(component.getInvariantUUID()); + asset.setName(component.getName()); + asset.setVersion(component.getVersion()); + if (!detailed) { + asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); + } else { + String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); + asset.setToscaModelURL(toscaModelUrl); + } + + return asset; + } + + private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); + if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + CategoryDefinition categoryDefinition = resource.getCategories().get(0); + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName()); + } + assetToPopulate.setResourceType(resource.getResourceType().name()); + assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); + + return (T) assetToPopulate; + } + + private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); + + if(service.getCategories() != null && !service.getCategories().isEmpty()){ + CategoryDefinition categoryDefinition = service.getCategories().get(0); + assetToPopulate.setCategory(categoryDefinition.getName()); + } + + assetToPopulate.setLifecycleState(service.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); + assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); + + return (T) assetToPopulate; + } + + private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { + + List<ComponentInstance> componentInstances = resource.getComponentInstances(); + + if (componentInstances != null) { + Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); + assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); + assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); + assetToPopulate.setDescription(resource.getDescription()); + return Either.left(assetToPopulate); + } + + private <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { + + List<ComponentInstance> componentInstances = service.getComponentInstances(); + + if (componentInstances != null) { + Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts(); + assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); + + return Either.left(assetToPopulate); + } + + private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map<String, ArtifactDefinition> artifacts) { + + List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(resource, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service, Map<String, ArtifactDefinition> artifacts) { + + List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(service, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) { + List<ArtifactMetadata> artifactMetaList = new LinkedList<>(); + if (artifacts != null) { + Collection<ArtifactDefinition> artefactDefList = artifacts.values(); + + for (ArtifactDefinition artifactDefinition : artefactDefList) { + if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { + ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); + artifactMetaList.add(convertedArtifactMetadata); + } + } + } + return artifactMetaList.isEmpty() ? null : artifactMetaList; + } + + private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { + final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; + + final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + + ArtifactMetadata metadata = new ArtifactMetadata(); + + metadata.setArtifactName(artifact.getArtifactName()); + metadata.setArtifactType(artifact.getArtifactType()); + + if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { + metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); + } else { + metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); + } + + metadata.setArtifactDescription(artifact.getDescription()); + metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); + metadata.setArtifactChecksum(artifact.getArtifactChecksum()); + metadata.setArtifactUUID(artifact.getArtifactUUID()); + metadata.setArtifactVersion(artifact.getArtifactVersion()); + metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); + metadata.setArtifactLabel(artifact.getArtifactLabel()); + metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); + return metadata; + } + + private Either<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) { + List<ResourceInstanceMetadata> retList = new LinkedList<>(); + Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>(); + + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); + String componentUid = componentInstance.getComponentUid(); + String invariantUUID, resourceUUID; + + if (!uuidDuplicatesMap.containsKey(componentUid)) { + Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); + if (eitherResource.isRight()) { + log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); + return Either.right(eitherResource.right().value()); + } else { + final Resource resource = eitherResource.left().value(); + invariantUUID = resource.getInvariantUUID(); + resourceUUID = resource.getUUID(); + ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); + uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); + } + } else { + invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); + resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); + } + + metadata.setResourceInvariantUUID(invariantUUID); + metadata.setResourceUUID(resourceUUID); + metadata.setResourceInstanceName(componentInstance.getName()); + metadata.setResourceName(componentInstance.getComponentName()); + metadata.setResourceVersion(componentInstance.getComponentVersion()); + metadata.setResoucreType(componentInstance.getOriginType().getValue()); + + if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ + LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>(); + Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values(); + for (ArtifactDefinition artifactDefinition : values) { + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); + artifactMetaList.add(converted); + } + metadata.setArtifacts(artifactMetaList); + } + retList.add(metadata); + } + return Either.left(retList); + } + + // For future US to support Product + /* + * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); + * + * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); + * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); + * + * List<CategoryDefinition> categories = product.getCategories(); List<ProductCategoryGroupMetadata> categoryMetadataList = new LinkedList<>(); + * + * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List<SubCategoryDefinition> subcategories = + * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List<GroupDefinition> groups = product.getGroups(); for (GroupDefinition + * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); + * return retProdAsset; } } + */ } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java index 4ee3605703..6b0c85bb3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java @@ -27,26 +27,26 @@ import org.slf4j.LoggerFactory; public final class EcompRoleConverter { - private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName()); - - private EcompRoleConverter() { - } - - // TODO Add Either or Exception in case of convertation failure - public static String convertEcompRoleToRole(EcompRole ecompRole) { - - log.debug("converting role"); - if (ecompRole == null) { - log.debug("recieved null for roles"); - return null; - } - - for (Role role : Role.values()) { - if (role.ordinal() == ecompRole.getId()) { - return role.name(); - } - } - log.debug("no roles converted"); - return null; - } + private static final Logger log = LoggerFactory.getLogger(EcompRoleConverter.class); + + private EcompRoleConverter() { + } + + // TODO Add Either or Exception in case of convertation failure + public static String convertEcompRoleToRole(EcompRole ecompRole) { + + log.debug("converting role"); + if (ecompRole == null) { + log.debug("recieved null for roles"); + return null; + } + + for (Role role : Role.values()) { + if (role.ordinal() == ecompRole.getId()) { + return role.name(); + } + } + log.debug("no roles converted"); + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java index 19ef31feaf..590be72f1f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java @@ -20,91 +20,90 @@ package org.openecomp.sdc.be.ecomp.converters; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - +import fj.data.Either; import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; -import fj.data.Either; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; public final class EcompUserConverter { - private EcompUserConverter() { - } - - public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) { - EcompUser convertedUser = new EcompUser(); - - if (asdcUser == null) { - return Either.right("User is null"); - } - - convertedUser.setFirstName(asdcUser.getFirstName()); - convertedUser.setLastName(asdcUser.getLastName()); - convertedUser.setLoginId(asdcUser.getUserId()); - convertedUser.setOrgUserId(asdcUser.getUserId()); - convertedUser.setEmail(asdcUser.getEmail()); - - if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) { - convertedUser.setActive(true); - } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) { - convertedUser.setActive(false); - } - - EcompRole convertedRole = new EcompRole(); - for (Role role : Role.values()) { - if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) { - convertedRole.setName(role.name()); - convertedRole.setId(new Long(role.ordinal())); - break; - } - } - - Set<EcompRole> convertedRoleSet = new HashSet<>(); - convertedRoleSet.add(convertedRole); - convertedUser.setRoles(convertedRoleSet); - - return Either.left(convertedUser); - } - - public static Either<User, String> convertEcompUserToUser(EcompUser ecompUser) { - User convertedUser = new User(); - - if (ecompUser == null) { - return Either.right("EcompUser is null"); - } - - convertedUser.setFirstName(ecompUser.getFirstName()); - convertedUser.setLastName(ecompUser.getLastName()); - - if (!ecompUser.getLoginId().isEmpty()) { - convertedUser.setUserId(ecompUser.getLoginId()); - } else { - convertedUser.setUserId(ecompUser.getOrgUserId()); - } - - convertedUser.setEmail(ecompUser.getEmail()); - - if (ecompUser.getRoles() != null) { - Iterator<EcompRole> iter = ecompUser.getRoles().iterator(); - - if (iter.hasNext()) { - String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next()); - convertedUser.setRole(updatedRole); - } - } - - if (ecompUser.isActive()) { - convertedUser.setStatus(UserStatusEnum.ACTIVE); - } else { - convertedUser.setStatus(UserStatusEnum.INACTIVE); - } - - return Either.left(convertedUser); - } + private EcompUserConverter() { + } + + public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) { + EcompUser convertedUser = new EcompUser(); + + if (asdcUser == null) { + return Either.right("User is null"); + } + + convertedUser.setFirstName(asdcUser.getFirstName()); + convertedUser.setLastName(asdcUser.getLastName()); + convertedUser.setLoginId(asdcUser.getUserId()); + convertedUser.setOrgUserId(asdcUser.getUserId()); + convertedUser.setEmail(asdcUser.getEmail()); + + if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) { + convertedUser.setActive(true); + } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) { + convertedUser.setActive(false); + } + + EcompRole convertedRole = new EcompRole(); + for (Role role : Role.values()) { + if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) { + convertedRole.setName(role.name()); + convertedRole.setId(new Long(role.ordinal())); + break; + } + } + + Set<EcompRole> convertedRoleSet = new HashSet<>(); + convertedRoleSet.add(convertedRole); + convertedUser.setRoles(convertedRoleSet); + + return Either.left(convertedUser); + } + + public static Either<User, String> convertEcompUserToUser(EcompUser ecompUser) { + User convertedUser = new User(); + + if (ecompUser == null) { + return Either.right("EcompUser is null"); + } + + convertedUser.setFirstName(ecompUser.getFirstName()); + convertedUser.setLastName(ecompUser.getLastName()); + + if (!ecompUser.getLoginId().isEmpty()) { + convertedUser.setUserId(ecompUser.getLoginId()); + } else { + convertedUser.setUserId(ecompUser.getOrgUserId()); + } + + convertedUser.setEmail(ecompUser.getEmail()); + + if (ecompUser.getRoles() != null) { + Iterator<EcompRole> iter = ecompUser.getRoles().iterator(); + + if (iter.hasNext()) { + String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next()); + convertedUser.setRole(updatedRole); + } + } + + if (ecompUser.isActive()) { + convertedUser.setStatus(UserStatusEnum.ACTIVE); + } else { + convertedUser.setStatus(UserStatusEnum.INACTIVE); + } + + return Either.left(convertedUser); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java index 1408459470..70225c0dd2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java @@ -20,26 +20,15 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -56,16 +45,24 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; /** * This Servlet serves external users operations on artifacts. * @@ -78,740 +75,740 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ArtifactExternalServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class); + + private static String startLog = "Start handle request of "; + + /** + * Uploads an artifact to resource or service + * + * @param contenType + * @param checksum + * @param userId + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @param data + * @return + */ + @POST + @Path("/{assetType}/{uuid}/artifacts") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response uploadArtifact( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + String data) { + + init(log); - private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName()); - - private static String startLog = "Start handle request of "; + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - /** - * Uploads an artifact to resource or service - * - * @param contenType - * @param checksum - * @param userId - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @param data - * @return - */ - @POST - @Path("/{assetType}/{uuid}/artifacts") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response uploadArtifact( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - String data) { - - init(log); - - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - if (componentType == null) { - log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - if (responseWrapper.isEmpty() ) { - validateHttpCspUserIdHeader(userId, responseWrapper); - } - Response response = null; - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to upload artifact"); - responseWrapper.setInnerElement(uploadArtifactEither.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK)); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers); - } - } - if( response == null ){ - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - return response; - } catch (Exception e) { - final String message = "failed to upload artifact to a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams); - } - } + if (componentType == null) { + log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + if (responseWrapper.isEmpty() ) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + Response response = null; + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to upload artifact"); + responseWrapper.setInnerElement(uploadArtifactEither.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK)); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers); + } + } + if( response == null ){ + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + return response; + } catch (Exception e) { + final String message = "failed to upload artifact to a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams); + } + } - /** - * Uploads an artifact to resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @return - */ - @POST - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response uploadArtifactToInstance( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, - String data) { + /** + * Uploads an artifact to resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @return + */ + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response uploadArtifactToInstance( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, + String data) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - if (componentType == null) { - log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("uploadArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to upload artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - }catch (Exception e) { - final String message = "failed to upload artifact to a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + if (componentType == null) { + log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("uploadArtifact: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to upload artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + }catch (Exception e) { + final String message = "failed to upload artifact to a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * - * @param contenType - * @param checksum - * @param userId - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @param artifactUUID - * @param data - * @return - */ - @POST - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response updateArtifact( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - String data) { + /** + * + * @param contenType + * @param checksum + * @param userId + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @param artifactUUID + * @param data + * @return + */ + @POST + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response updateArtifact( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + String data) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("updateArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("updateArtifact: Missing USER_ID"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to update artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to update artifact on a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("updateArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("updateArtifact: Missing USER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to update artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to update artifact on a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * updates an artifact on a resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @param artifactUUID - * @return - */ - @POST - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response updateArtifactOnResourceInstance( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, - String data) { + /** + * updates an artifact on a resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @param artifactUUID + * @return + */ + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response updateArtifactOnResourceInstance( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, + String data) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("updateArtifactOnResourceInstance: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to update artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to update artifact on resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("updateArtifactOnResourceInstance: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to update artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to update artifact on resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * deletes an artifact of a resource or service - * - * @param assetType - * @param uuid - * @param artifactUUID - * @return - */ - @DELETE - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class) - /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Asset not found") })*/ - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - public Response deleteArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { + /** + * deletes an artifact of a resource or service + * + * @param assetType + * @param uuid + * @param artifactUUID + * @return + */ + @DELETE + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class) + /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Asset not found") })*/ + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + public Response deleteArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("deleteArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to delete artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("deleteArtifact: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to delete artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * deletes an artifact of a resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @return - */ - @DELETE - @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - public Response deleteArtifactOnResourceInstance( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { + /** + * deletes an artifact of a resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @return + */ + @DELETE + @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + public Response deleteArtifactOnResourceInstance( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to delete artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to delete artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * downloads an artifact of a component (either a service or a resource) by artifactUUID - * - * @param assetType - * @param uuid - * @param artifactUUID - * @return - */ - @GET - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) - public Response downloadComponentArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { + /** + * downloads an artifact of a component (either a service or a resource) by artifactUUID + * + * @param assetType + * @param uuid + * @param artifactUUID + * @return + */ + @GET + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) + public Response downloadComponentArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams); - if (downloadComponentArtifactEither.isRight()) { - responseFormat = downloadComponentArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - byte[] value = downloadComponentArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); - } - } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams); + if (downloadComponentArtifactEither.isRight()) { + responseFormat = downloadComponentArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + byte[] value = downloadComponentArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); + } + } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @param artifactUUID - * @return - */ - @GET - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(nickname = "downloadResourceInstanceArtifactByUUID",value = "Download resource instance artifact by artifact UUID", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) - public Response downloadResourceInstanceArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { + /** + * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @param artifactUUID + * @return + */ + @GET + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) + public Response downloadResourceInstanceArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { - Wrapper<Response> responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); - if (downloadResourceArtifactEither.isRight()) { - responseFormat = downloadResourceArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - byte[] value = downloadResourceArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); - } - } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper<Response> responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); + if (downloadResourceArtifactEither.isRight()) { + responseFormat = downloadResourceArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + byte[] value = downloadResourceArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); + } + } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java index b9956063d6..27f82dfda3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java @@ -20,26 +20,9 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; @@ -61,14 +44,19 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * This Servlet serves external users for retrieving component metadata. @@ -83,311 +71,299 @@ import io.swagger.annotations.ApiResponses; @Singleton public class AssetsDataServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - - private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName()); - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param category - * @param subCategory - * @param distributionStatus - * @param resourceType - * @return - */ - @GET - @Path("/{assetType}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getAssetListExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) { - - Response response = null; - ResponseFormat responseFormat = null; - String query = request.getQueryString(); - String requestURI = request.getRequestURI().endsWith("/")? - removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST; - - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query); - - // Mandatory - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ServletContext context = request.getSession().getServletContext(); - ElementBusinessLogic elementLogic = getElementBL(context); - - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class); - - if (category != null) { - filters.put(FilterKeyEnum.CATEGORY, category); - } - if (subCategory != null) { - filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory); - } - if (distributionStatus != null) { - filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus); - } - if (resourceType != null) { - ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType); - if (resourceTypeEnum == null) { - log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); - } - - Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query); - - if (assetTypeData.isRight()) { - log.debug("getAssetList: Asset Fetching Failed"); - responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } else { - log.debug("getAssetList: Asset Fetching Success"); - Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); - if (resMetadata.isRight()) { - log.debug("getAssetList: Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - response = buildOkResponse(responseFormat, result); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); - log.debug("getAssetList: Fetch list of assets failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @return - */ - @GET - @Path("/{assetType}/{uuid}/metadata") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getAssetSpecificMetadataByUuidExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { - - Response response = null; - ResponseFormat responseFormat = null; - AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - if (componentType == null) { - log.debug("getMetaData: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); - - // Mandatory - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ServletContext context = request.getSession().getServletContext(); - ElementBusinessLogic elementLogic = getElementBL(context); - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - - Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - - if (assetTypeData.isRight()) { - log.debug("getAssetList: Asset Fetching Failed"); - responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - return buildErrorResponse(responseFormat); - } else { - log.debug("getAssetList: Asset Fetching Success"); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName()); - Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); - if (resMetadata.isRight()) { - log.debug("getAssetList: Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next()); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - response = buildOkResponse(responseFormat, result); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); - log.debug("getAssetList: Fetch list of assets failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @return - */ - @GET - @Path("/{assetType}/{uuid}/toscaModel") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getToscaModelExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { - - String url = request.getRequestURI(); - log.debug("Start handle request of {} {}", request.getMethod(), url); - Response response = null; - ResponseFormat responseFormat = null; - ServletContext context = request.getSession().getServletContext(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - - if (componentType == null) { - log.debug("getToscaModel: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); - - - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getToscaModel: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ComponentBusinessLogic componentBL = getComponentBL(componentType, context); - - Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam); - if (csarArtifact.isRight()) { - responseFormat = csarArtifact.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = csarArtifact.left().value().getRight(); - InputStream is = new ByteArrayInputStream(value); - String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value); - Map<String, String> headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft())); - headers.put(Constants.MD5_HEADER, contenetMD5); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model"); - log.debug("falied to get asset tosca model", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - response = buildErrorResponse(responseFormat); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return response; - } - } - - - private String removeDuplicateSlashSeparator(String requestUri) { - return requestUri.substring(0, requestUri.length()-1); - } + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(AssetsDataServlet.class); + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param category + * @param subCategory + * @param distributionStatus + * @param resourceType + * @return + */ + @GET + @Path("/{assetType}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getAssetListExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) { + + Response response = null; + ResponseFormat responseFormat = null; + String query = request.getQueryString(); + String requestURI = request.getRequestURI().endsWith("/")? + removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST; + + EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query); + + // Mandatory + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ElementBusinessLogic elementLogic = getElementBL(context); + + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class); + + if (category != null) { + filters.put(FilterKeyEnum.CATEGORY, category); + } + if (subCategory != null) { + filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory); + } + if (distributionStatus != null) { + filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus); + } + if (resourceType != null) { + ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType); + if (resourceTypeEnum == null) { + log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); + } + + Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query); + + if (assetTypeData.isRight()) { + log.debug("getAssetList: Asset Fetching Failed"); + responseFormat = assetTypeData.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } else { + log.debug("getAssetList: Asset Fetching Success"); + Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); + if (resMetadata.isRight()) { + log.debug("getAssetList: Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + response = buildOkResponse(responseFormat, result); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); + log.debug("getAssetList: Fetch list of assets failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @return + */ + @GET + @Path("/{assetType}/{uuid}/metadata") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getAssetSpecificMetadataByUuidExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { + + Response response = null; + ResponseFormat responseFormat = null; + AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); + + // Mandatory + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ElementBusinessLogic elementLogic = getElementBL(context); + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + + Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); + + if (assetTypeData.isRight()) { + log.debug("getAssetList: Asset Fetching Failed"); + responseFormat = assetTypeData.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + return buildErrorResponse(responseFormat); + } else { + log.debug("getAssetList: Asset Fetching Success"); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName()); + Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); + if (resMetadata.isRight()) { + log.debug("getAssetList: Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next()); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + response = buildOkResponse(responseFormat, result); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); + log.debug("getAssetList: Fetch list of assets failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @return + */ + @GET + @Path("/{assetType}/{uuid}/toscaModel") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getToscaModelExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { + + String url = request.getRequestURI(); + log.debug("Start handle request of {} {}", request.getMethod(), url); + Response response = null; + ResponseFormat responseFormat = null; + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL; + EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); + + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getToscaModel: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ComponentBusinessLogic componentBL = getComponentBL(componentType, context); + + Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam); + if (csarArtifact.isRight()) { + responseFormat = csarArtifact.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = csarArtifact.left().value().getRight(); + InputStream is = new ByteArrayInputStream(value); + String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value); + Map<String, String> headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft())); + headers.put(Constants.MD5_HEADER, contenetMD5); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + response = buildOkResponse(responseFormat, is, headers); + } + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model"); + log.debug("falied to get asset tosca model", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + response = buildErrorResponse(responseFormat); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return response; + } + } + + + private String removeDuplicateSlashSeparator(String requestUri) { + return requestUri.substring(0, requestUri.length()-1); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java index 18422f53a1..0651291fc4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java @@ -20,30 +20,11 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.IOException; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.commons.lang3.StringUtils; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.elasticsearch.common.Strings; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -62,11 +43,7 @@ import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -82,508 +59,509 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "CRUD External Servlet", description = "This Servlet serves external users for creating assets and changing their lifecycle state") @Singleton public class CrudExternalServlet extends AbstractValidationsServlet { - - @Context - private HttpServletRequest request; - - private static Logger log = LoggerFactory.getLogger(CrudExternalServlet.class.getName()); - - /** - * Creates a new Resource - * - * @param assetType - * @param data - * @param userId - * @param instanceIdHeader - * @return - */ - @POST - @Path("/{assetType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class), - @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), - @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), - @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), - @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource") - public Response createResourceExternal( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - String data) { - - init(log); - - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - Resource resource = null; - User modifier = null; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - ServletContext context = request.getSession().getServletContext(); - ResourceBusinessLogic resourceBL = getResourceBL(context); - try { - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - // Validate USER_ID Header - if (responseWrapper.isEmpty()) { - validateHttpCspUserIdHeader(userId, responseWrapper); - } - // Validate assetType - if (responseWrapper.isEmpty()) { - if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - //Validate resource type - if(responseWrapper.isEmpty()){ - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) parser.parse(data); - String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName()); - if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name")); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - // Convert the user json to a resource - if (responseWrapper.isEmpty()) { - modifier = new User(); - modifier.setUserId(userId); - Either<Resource, ResponseFormat> eitherResource = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, - null, ComponentTypeEnum.RESOURCE); - if( eitherResource.isRight() ){ - responseWrapper.setInnerElement(eitherResource.right().value()); - } - else{ - resource = eitherResource.left().value(); - } - - } - //validate name exist - if(responseWrapper.isEmpty()){ - if( Strings.isEmpty(resource.getName())){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); - - } - } - - if(responseWrapper.isEmpty()){ - resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root")); - resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName())); - resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), - resource.getSystemName())); - handleCategories(context, data, resource, responseWrapper); - } - // Create the resource in the dataModel - if (responseWrapper.isEmpty()) { - Either<Resource, ResponseFormat> eitherCreateResponse = resourceBL.createResource(resource, null, - modifier, null, null); - if (eitherCreateResponse.isRight()) { - responseWrapper.setInnerElement(eitherCreateResponse.right().value()); - } else { - resource = eitherCreateResponse.left().value(); - } - } - Response response; - //Build Response and store it in the response Wrapper - if (responseWrapper.isEmpty()) { - response = buildCreatedResourceResponse(resource, context, responseWrapper); - } - else{ - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - return response; - - } catch (Exception e) { - final String message = "failed to create vfc monitoring template resource"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - finally{ - prepareAdditionalAudit(resource, additionalParams); - - getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), - ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request, - additionalParams); - } - } - - /** - * Changing the lifecycle of an asset - * @param jsonChangeInfo The description - request body - * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources") - * @param uuid The uuid of the desired resource to be changed - * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST - * @param userId - * @return - */ - @POST - @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class), - @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed") - public Response changeResourceStateExternal( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid, - @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType, - String jsonChangeInfo) { - - Response response = null; - EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - init(log); - - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - //get the business logic - ServletContext context = request.getSession().getServletContext(); - LifecycleBusinessLogic businessLogic = getLifecycleBL(context); - - Wrapper<ResponseFormat> responseWrapper = runValidations(assetType); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - Component component = null; - Component responseObject = null; - User modifier = null; - - try{ - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - - if (responseWrapper.isEmpty()) { - //get user - Either<User, ResponseFormat> eitherGetUser = getUser(request, userId); - if (eitherGetUser.isRight()) { - ResponseFormat responseFormat = eitherGetUser.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - modifier = eitherGetUser.left().value(); - - //get the component id from the uuid - Either<Component, ResponseFormat> latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid); - if (latestVersion.isRight()) { - ResponseFormat responseFormat = latestVersion.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - component = latestVersion.left().value(); - String componentId = component.getUniqueId(); - - //validate the transition is valid - Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier); - if (validateEnum.isRight()) { - ResponseFormat responseFormat = validateEnum.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); - - //create changeInfo - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); - try { - if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); - } - } - catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", jsonChangeInfo, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - - //execute business logic - Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); - if (actionResponse.isRight()) { - log.info("failed to change resource state"); - ResponseFormat responseFormat = actionResponse.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - - log.debug("change state successful !!!"); - responseObject = actionResponse.left().value(); - response = buildCreatedResourceResponse(responseObject, context, responseWrapper); - } else { - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); - log.debug("change lifecycle state failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } finally{ - auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId); - } - } - - private void prepareAdditionalAudit(Resource resource, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY); - - if( resource != null ){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY); - } - } - - private Response buildCreatedResourceResponse(Component resource, ServletContext context, - Wrapper<ResponseFormat> responseWrapper) throws IOException, JsonGenerationException, JsonMappingException { - ResponseFormat responseFormat; - Response response; - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils - .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), - true); - if (resMetadata.isRight()) { - log.debug("Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - responseWrapper.setInnerElement(responseFormat); - response = buildErrorResponse(responseFormat); - }else{ - final AssetMetadata assetData = resMetadata.left().value(); - assetData.setToscaModelURL(null); - - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); - Object representation = RepresentationUtils.toRepresentation(assetData); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); - } - return response; - } - - private void handleCategories(ServletContext context, String data, Resource resource, - Wrapper<ResponseFormat> responseWrapper) { - try { - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) parser.parse(data); - String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue()); - String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue()); - if (Strings.isEmpty(category)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - else if (Strings.isEmpty(subcategory)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); - } - if (responseWrapper.isEmpty()) { - ElementBusinessLogic elementLogic = getElementBL(context); - // get All Categories - Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementLogic - .getAllResourceCategories(); - // Error fetching categories - if (allResourceCategories.isRight()) { - responseWrapper.setInnerElement( - getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); - } else { - addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); - } - } - } catch (Exception e) { - log.debug("Exception occured in addCategories: {}", e.getMessage(), e); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - private void addCategories(Resource resource, String category, String subcategory, - Either<List<CategoryDefinition>, ActionStatus> allResourceCategories, - Wrapper<ResponseFormat> responseWrapper) { - Optional<CategoryDefinition> optionalCategory = - // Stream of all the categories - allResourceCategories.left().value().stream() - // filter in only relevant category - .filter(e -> e.getName().equals(category)) - // get the result - .findAny(); - if (!optionalCategory.isPresent()) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } else { - CategoryDefinition categoryDefinition = optionalCategory.get(); - - List<SubCategoryDefinition> subCaregories = - // Stream of all sub-categories of the relevant - // category - categoryDefinition.getSubcategories().stream() - // filter in only relevant sub-category - .filter(e -> e.getName().equals(subcategory)) - // get the result - .collect(Collectors.toList()); - - if( subCaregories.isEmpty() ){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - else{ - categoryDefinition.setSubcategories(subCaregories); - resource.setCategories(Arrays.asList(categoryDefinition)); - } - - } - } - - - - - private void auditChnageLifecycleAction(EnumMap<AuditingFieldsKeysEnum, Object> additionalParams, - Wrapper<ResponseFormat> responseWrapper, ComponentTypeEnum componentType, Component component, - Component responseObject, User modifier, String userId) { - if (modifier!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId); - } - - if (component!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); - } - - if (responseObject!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name()); - } else { - if (component!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,""); - } - } - - getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), - componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request, - additionalParams); - } - - private Wrapper<ResponseFormat> runValidations(final String assetType) { - Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); - - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); - validateXECOMPInstanceIDHeader(instanceId,responseWrapper); - } - // Validate USER_ID Header - if (responseWrapper.isEmpty()) { - validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); - } - // Validate assetType - if (responseWrapper.isEmpty()) { - if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - - return responseWrapper; - } - - private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) { - LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; - try { - transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); - } catch (IllegalArgumentException e) { - log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(error); - } - return Either.left(transitionEnum); - } + + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(CrudExternalServlet.class); + + /** + * Creates a new Resource + * + * @param assetType + * @param data + * @param userId + * @param instanceIdHeader + * @return + */ + @POST + @Path("/{assetType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), + @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource")}) + public Response createResourceExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + String data) { + + init(log); + + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + Resource resource = null; + User modifier = null; + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + ServletContext context = request.getSession().getServletContext(); + ResourceBusinessLogic resourceBL = getResourceBL(context); + try { + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + //Validate resource type + if(responseWrapper.isEmpty()){ + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName()); + if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name")); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + // Convert the user json to a resource + if (responseWrapper.isEmpty()) { + modifier = new User(); + modifier.setUserId(userId); + Either<Resource, ResponseFormat> eitherResource = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, + null, ComponentTypeEnum.RESOURCE); + if( eitherResource.isRight() ){ + responseWrapper.setInnerElement(eitherResource.right().value()); + } + else{ + resource = eitherResource.left().value(); + } + + } + //validate name exist + if(responseWrapper.isEmpty()){ + if( Strings.isEmpty(resource.getName())){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); + + } + } + + if(responseWrapper.isEmpty()){ + resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root")); + resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName())); + resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), + resource.getSystemName())); + handleCategories(context, data, resource, responseWrapper); + } + // Create the resource in the dataModel + if (responseWrapper.isEmpty()) { + Either<Resource, ResponseFormat> eitherCreateResponse = resourceBL.createResource(resource, null, + modifier, null, null); + if (eitherCreateResponse.isRight()) { + responseWrapper.setInnerElement(eitherCreateResponse.right().value()); + } else { + resource = eitherCreateResponse.left().value(); + } + } + Response response; + //Build Response and store it in the response Wrapper + if (responseWrapper.isEmpty()) { + response = buildCreatedResourceResponse(resource, context, responseWrapper); + } + else{ + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + return response; + + } catch (Exception e) { + final String message = "failed to create vfc monitoring template resource"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + finally{ + prepareAdditionalAudit(resource, additionalParams); + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request, + additionalParams); + } + } + + /** + * Changing the lifecycle of an asset + * @param jsonChangeInfo The description - request body + * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources") + * @param uuid The uuid of the desired resource to be changed + * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST + * @param userId + * @return + */ + @POST + @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")}) + public Response changeResourceStateExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid, + @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType, + String jsonChangeInfo) { + + Response response = null; + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + + init(log); + + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + //get the business logic + ServletContext context = request.getSession().getServletContext(); + LifecycleBusinessLogic businessLogic = getLifecycleBL(context); + + Wrapper<ResponseFormat> responseWrapper = runValidations(assetType); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + Component component = null; + Component responseObject = null; + User modifier = null; + + try{ + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + + if (responseWrapper.isEmpty()) { + //get user + Either<User, ResponseFormat> eitherGetUser = getUser(request, userId); + if (eitherGetUser.isRight()) { + ResponseFormat responseFormat = eitherGetUser.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + modifier = eitherGetUser.left().value(); + + //get the component id from the uuid + Either<Component, ResponseFormat> latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid); + if (latestVersion.isRight()) { + ResponseFormat responseFormat = latestVersion.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + component = latestVersion.left().value(); + String componentId = component.getUniqueId(); + + //validate the transition is valid + Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier); + if (validateEnum.isRight()) { + ResponseFormat responseFormat = validateEnum.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); + + //create changeInfo + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); + try { + if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); + } + } + catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", jsonChangeInfo, e); + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + //execute business logic + Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); + if (actionResponse.isRight()) { + log.info("failed to change resource state"); + ResponseFormat responseFormat = actionResponse.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + log.debug("change state successful !!!"); + responseObject = actionResponse.left().value(); + response = buildCreatedResourceResponse(responseObject, context, responseWrapper); + } else { + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); + log.debug("change lifecycle state failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } finally{ + auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId); + } + } + + private void prepareAdditionalAudit(Resource resource, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY); + + if( resource != null ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY); + } + } + + private Response buildCreatedResourceResponse(Component resource, ServletContext context, + Wrapper<ResponseFormat> responseWrapper) throws IOException { + ResponseFormat responseFormat; + Response response; + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils + .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), + true); + if (resMetadata.isRight()) { + log.debug("Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + responseWrapper.setInnerElement(responseFormat); + response = buildErrorResponse(responseFormat); + }else{ + final AssetMetadata assetData = resMetadata.left().value(); + assetData.setToscaModelURL(null); + + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); + Object representation = RepresentationUtils.toRepresentation(assetData); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); + } + return response; + } + + private void handleCategories(ServletContext context, String data, Resource resource, + Wrapper<ResponseFormat> responseWrapper) { + try { + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue()); + String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue()); + if (Strings.isEmpty(category)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else if (Strings.isEmpty(subcategory)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); + } + if (responseWrapper.isEmpty()) { + ElementBusinessLogic elementLogic = getElementBL(context); + // get All Categories + Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementLogic + .getAllResourceCategories(); + // Error fetching categories + if (allResourceCategories.isRight()) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); + } else { + addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); + } + } + } catch (Exception e) { + log.debug("Exception occured in addCategories: {}", e.getMessage(), e); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + private void addCategories(Resource resource, String category, String subcategory, + Either<List<CategoryDefinition>, ActionStatus> allResourceCategories, + Wrapper<ResponseFormat> responseWrapper) { + Optional<CategoryDefinition> optionalCategory = + // Stream of all the categories + allResourceCategories.left().value().stream() + // filter in only relevant category + .filter(e -> e.getName().equals(category)) + // get the result + .findAny(); + if (!optionalCategory.isPresent()) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } else { + CategoryDefinition categoryDefinition = optionalCategory.get(); + + List<SubCategoryDefinition> subCaregories = + // Stream of all sub-categories of the relevant + // category + categoryDefinition.getSubcategories().stream() + // filter in only relevant sub-category + .filter(e -> e.getName().equals(subcategory)) + // get the result + .collect(Collectors.toList()); + + if( subCaregories.isEmpty() ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else{ + categoryDefinition.setSubcategories(subCaregories); + resource.setCategories(Arrays.asList(categoryDefinition)); + } + + } + } + + + + + private void auditChnageLifecycleAction(EnumMap<AuditingFieldsKeysEnum, Object> additionalParams, + Wrapper<ResponseFormat> responseWrapper, ComponentTypeEnum componentType, Component component, + Component responseObject, User modifier, String userId) { + if (modifier!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId); + } + + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); + } + + if (responseObject!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name()); + } else { + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,""); + } + } + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request, + additionalParams); + } + + private Wrapper<ResponseFormat> runValidations(final String assetType) { + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); + validateXECOMPInstanceIDHeader(instanceId,responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + + return responseWrapper; + } + + private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) { + LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; + try { + transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); + } catch (IllegalArgumentException e) { + log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(error); + } + return Either.left(transitionEnum); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java new file mode 100644 index 0000000000..7e48890c7d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java @@ -0,0 +1,214 @@ +package org.openecomp.sdc.be.externalapi.servlet; + +import fj.data.Either; +import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; +import java.util.Map; + + +@Path("/v1/catalog") +@Controller +public class ExternalRefsServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(ExternalRefsServlet.class); + + private ExternalRefsBusinessLogic businessLogic; + + public ExternalRefsServlet(ExternalRefsBusinessLogic businessLogic, ComponentsUtils componentsUtils){ + this.businessLogic = businessLogic; + this.componentsUtils = componentsUtils; + } + + @GET + @Path("/{assetType}/{uuid}/version/{version}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}") + @Produces(MediaType.APPLICATION_JSON) + public Response getComponentInstanceExternalRef( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("version") String version, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) { + + log.debug("GET component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either<List<String>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, componentInstanceName, objectType); + if (refsResult.isLeft()){ + return this.buildOkResponse(refsResult.left().value()); + } else { + return this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, componentInstanceName, objectType, ""); + } + } + + @GET + @Path("/{assetType}/{uuid}/version/{version}/externalReferences/{objectType}") + @Produces(MediaType.APPLICATION_JSON) + public Map<String, List<String>> getAssetExternalRefByObjectType( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("version") String version, + @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) { + + log.debug("GET asset external references {} {} {}", assetType, uuid, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + throw new WebApplicationException(r); + } + + Either<Map<String, List<String>>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, objectType); + if (refsResult.isLeft()){ + return refsResult.left().value(); + } else { + throw new WebApplicationException(this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, "", objectType, "")); + } + } + + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response addComponentInstanceExternalRef( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, ExternalRefDTO ref, @HeaderParam("USER_ID") String userId) { + + log.debug("POST component instance external interfaces {} {} {} {} {}", assetType, uuid, componentInstanceName, objectType, ref); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either<String, ActionStatus> addResult = this.businessLogic.addExternalReference(uuid, componentInstanceName, objectType, ref); + if (addResult.isLeft()) { + return Response.status(Response.Status.CREATED) + .entity(ref) + .build(); + } else { + return this.buildExtRefErrorResponse(addResult.right().value(), uuid, "", componentInstanceName, objectType, ref.getReferenceUUID()); + } + + } + + @DELETE + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{reference}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteComponentInstanceReference( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, + @PathParam("reference") String reference, @HeaderParam("USER_ID") String userId) { + + log.debug("DELETE component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either<String, ActionStatus> deleteStatus = this.businessLogic.deleteExternalReference(uuid, componentInstanceName, objectType, reference); + if (deleteStatus.isLeft()){ + return this.buildOkResponse(new ExternalRefDTO(reference)); + } else { + return this.buildExtRefErrorResponse(deleteStatus.right().value(), uuid, "", componentInstanceName, objectType, reference); + } + } + + @PUT + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{oldRefValue}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response updateComponentInstanceReference( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, + @PathParam("oldRefValue") String oldRefValue, + ExternalRefDTO newRefValueDTO, @HeaderParam("USER_ID") String userId) { + + log.debug("PUT component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + String newRefValue = newRefValueDTO.getReferenceUUID(); + Either<String, ActionStatus> updateResult = this.businessLogic.updateExternalReference(uuid, componentInstanceName, objectType, oldRefValue, newRefValue); + if (updateResult.isLeft()){ + return this.buildOkResponse(new ExternalRefDTO(newRefValue)); + } else { + return this.buildExtRefErrorResponse(updateResult.right().value(), uuid, "", componentInstanceName, objectType, oldRefValue); + } + + } + + private Response authorizeAndValidateRequest(final HttpServletRequest request, String userId) { + init(log); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<User> userWrapper = new Wrapper<>(); + + //Validate X-ECOMP_INSTANCE_ID_HEADER + if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null || request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER).isEmpty()){ + return this.buildExtRefErrorResponse(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID, "", "", "", "", ""); + } + + String method = request.getMethod(); + if (responseWrapper.isEmpty() && !"GET".equals(method)) { + validateUserExist(responseWrapper, userWrapper, userId); + validateUserRole(responseWrapper, userWrapper.getInnerElement()); + } + + return responseWrapper.getInnerElement(); + } + + private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType, String ref){ + switch (status) { + case RESOURCE_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid)); + case COMPONENT_VERSION_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid, version)); + case COMPONENT_INSTANCE_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, componentInstanceName, uuid)); + case EXT_REF_ALREADY_EXIST: + return Response.status(Response.Status.OK) + .entity(new ExternalRefDTO(ref)) + .build(); + case EXT_REF_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, objectType + "/" + ref)); + case MISSING_X_ECOMP_INSTANCE_ID: + return buildErrorResponse(componentsUtils.getResponseFormat(status)); + default: + return this.buildGeneralErrorResponse(); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java new file mode 100644 index 0000000000..3f1bf18edb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java @@ -0,0 +1,167 @@ +package org.openecomp.sdc.be.externalapi.servlet; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.EnumMap; + +/** + * Created by chaya on 10/17/2017. + */ +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service") +@Singleton +public class ServiceActivationServlet extends AbstractValidationsServlet { + + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(ServiceActivationServlet.class); + + /** + * Activates a service on a specific environment + * + * @param serviceUUID + * @param opEnvId + * @param userId + * @param instanceIdHeader + * @return + */ + @POST + @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "activate a service", httpMethod = "POST", notes = "Activates a service") + @ApiResponses(value = { + @ApiResponse(code = 202, message = "ECOMP component is authenticated and required service may be distributed"), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(code = 409, message = "Service state is invalid for this action"), + @ApiResponse(code = 502, message = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")}) + public Response activateServiceExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID, + @ApiParam(value = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId, + String data) { + + init(log); + + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + log.debug("Start handle request of {}", url); + + ServletContext context = request.getSession().getServletContext(); + try { + + Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId); + + if (responseWrapper.isEmpty()) { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + ServiceBusinessLogic businessLogic = getServiceBL(context); + ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data); + Either<String, ResponseFormat> distResponse = businessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata); + + if (distResponse.isRight()) { + log.debug("failed to activate service distribution"); + responseFormat = distResponse.right().value(); + return buildErrorResponse(responseFormat); + } + String distributionId = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED); + return buildOkResponse(responseFormat, result); + } else { + log.debug("request instanceId/userId header validation failed"); + responseFormat = responseWrapper.getInnerElement(); + return buildErrorResponse(responseFormat); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); + log.debug("activate distribution failed with exception", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } finally { + getComponentsUtils().auditExternalActivateService(responseFormat, ComponentTypeEnum.SERVICE.name(), request, additionalParams); + } + } + + private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) { + Wrapper<ResponseFormat> responseWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + return responseWrapper; + } + + private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue(data, ServiceDistributionReqInfo.class); + } catch (IOException e) { + log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e); + return new ServiceDistributionReqInfo(null); + } + } + + @Override + protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) { + ResponseFormat responseFormat; + if( StringUtils.isEmpty(header)){ + log.debug("MissingUSER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + responseWrapper.setInnerElement(responseFormat); + } + } +} + + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java index 15ebceaa5d..e41d8d7548 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java @@ -21,104 +21,104 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ArtifactMetadata { - private String artifactName; - private String artifactType; - private String artifactURL; - private String artifactDescription; - private Integer artifactTimeout; - private String artifactChecksum; - private String artifactUUID; - private String artifactVersion; - private String generatedFromUUID; - private String artifactLabel; - private String artifactGroupType; - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactType() { - return artifactType; - } - - public void setArtifactType(String artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public Integer getArtifactTimeout() { - return artifactTimeout; - } - - public void setArtifactTimeout(Integer artifactTimeout) { - this.artifactTimeout = artifactTimeout; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public void setArtifactChecksum(String artifactChecksum) { - this.artifactChecksum = artifactChecksum; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getGeneratedFromUUID() { - return generatedFromUUID; - } - - public void setGeneratedFromUUID(String generatedFromUUID) { - this.generatedFromUUID = generatedFromUUID; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public void setArtifactLabel(String artifactLabel) { - this.artifactLabel = artifactLabel; - } - - public String getArtifactGroupType() { - return artifactGroupType; - } - - public void setArtifactGroupType(String artifactGroupType) { - this.artifactGroupType = artifactGroupType; - } + private String artifactName; + private String artifactType; + private String artifactURL; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactChecksum; + private String artifactUUID; + private String artifactVersion; + private String generatedFromUUID; + private String artifactLabel; + private String artifactGroupType; + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java index cb14f76aff..b12411a7b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java @@ -21,109 +21,109 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public abstract class AssetMetadata implements IAssetMetadata { - private String uuid; - private String invariantUUID; - private String name; - private String version; - private String toscaModelURL; + private String uuid; + private String invariantUUID; + private String name; + private String version; + private String toscaModelURL; - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid() - */ - @Override - public String getUuid() { - return uuid; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid() + */ + @Override + public String getUuid() { + return uuid; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String) - */ - @Override - public void setUuid(String uuid) { - this.uuid = uuid; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String) + */ + @Override + public void setUuid(String uuid) { + this.uuid = uuid; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID() - */ - @Override - public String getInvariantUUID() { - return invariantUUID; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID() + */ + @Override + public String getInvariantUUID() { + return invariantUUID; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String) - */ - @Override - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String) + */ + @Override + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName() - */ - @Override - public String getName() { - return name; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName() + */ + @Override + public String getName() { + return name; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String) - */ - @Override - public void setName(String name) { - this.name = name; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String) + */ + @Override + public void setName(String name) { + this.name = name; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion() - */ - @Override - public String getVersion() { - return version; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion() + */ + @Override + public String getVersion() { + return version; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String) - */ - @Override - public void setVersion(String version) { - this.version = version; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String) + */ + @Override + public void setVersion(String version) { + this.version = version; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL() - */ - @Override - public String getToscaModelURL() { - return toscaModelURL; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL() + */ + @Override + public String getToscaModelURL() { + return toscaModelURL; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String) - */ - @Override - public void setToscaModelURL(String toscaModelURL) { - this.toscaModelURL = toscaModelURL; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String) + */ + @Override + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java index f95a8e9684..319e16a294 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java @@ -22,24 +22,24 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public interface IAssetMetadata { - String getUuid(); + String getUuid(); - void setUuid(String uuid); + void setUuid(String uuid); - String getInvariantUUID(); + String getInvariantUUID(); - void setInvariantUUID(String invariantUUID); + void setInvariantUUID(String invariantUUID); - String getName(); + String getName(); - void setName(String name); + void setName(String name); - String getVersion(); + String getVersion(); - void setVersion(String version); + void setVersion(String version); - String getToscaModelURL(); + String getToscaModelURL(); - void setToscaModelURL(String toscaModelURL); + void setToscaModelURL(String toscaModelURL); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java index d2d9c2c902..40b78c12d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java @@ -23,50 +23,50 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ProductAssetMetadata extends AssetMetadata { - private String lifecycleState; - private String lastUpdaterUserId; - private boolean isActive; - private List<String> contacts; - private List<ProductCategoryGroupMetadata> productGroupings; + private String lifecycleState; + private String lastUpdaterUserId; + private boolean isActive; + private List<String> contacts; + private List<ProductCategoryGroupMetadata> productGroupings; - public String getLifecycleState() { - return lifecycleState; - } + public String getLifecycleState() { + return lifecycleState; + } - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } - public boolean isActive() { - return isActive; - } + public boolean isActive() { + return isActive; + } - public void setActive(boolean isActive) { - this.isActive = isActive; - } + public void setActive(boolean isActive) { + this.isActive = isActive; + } - public List<String> getContacts() { - return contacts; - } + public List<String> getContacts() { + return contacts; + } - public void setContacts(List<String> contacts) { - this.contacts = contacts; - } + public void setContacts(List<String> contacts) { + this.contacts = contacts; + } - public List<ProductCategoryGroupMetadata> getProductGroupings() { - return productGroupings; - } + public List<ProductCategoryGroupMetadata> getProductGroupings() { + return productGroupings; + } - public void setProductGroupings(List<ProductCategoryGroupMetadata> productGroupings) { - this.productGroupings = productGroupings; - } + public void setProductGroupings(List<ProductCategoryGroupMetadata> productGroupings) { + this.productGroupings = productGroupings; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java index 047f9d6a2c..7d666df703 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java @@ -21,37 +21,37 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ProductCategoryGroupMetadata { - private String category; - private String subCategory; - private String group; - - public ProductCategoryGroupMetadata(String category, String subCategory, String group) { - this.category = category; - this.subCategory = subCategory; - this.group = group; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubCategory() { - return subCategory; - } - - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } - - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } + private String category; + private String subCategory; + private String group; + + public ProductCategoryGroupMetadata(String category, String subCategory, String group) { + this.category = category; + this.subCategory = subCategory; + this.group = group; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java index 0952feea05..eb15e077de 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java @@ -24,50 +24,50 @@ import java.util.List; public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata { - private String lastUpdaterFullName; - private String toscaResourceName; - private List<ResourceInstanceMetadata> resources; - private List<ArtifactMetadata> artifacts; - private String description; + private String lastUpdaterFullName; + private String toscaResourceName; + private List<ResourceInstanceMetadata> resources; + private List<ArtifactMetadata> artifacts; + private String description; - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } - public String getToscaResourceName() { - return toscaResourceName; - } + public String getToscaResourceName() { + return toscaResourceName; + } - public void setToscaResourceName(String toscaResourceName) { - this.toscaResourceName = toscaResourceName; - } + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } - public List<ResourceInstanceMetadata> getResources() { - return resources; - } + public List<ResourceInstanceMetadata> getResources() { + return resources; + } - public void setResources(List<ResourceInstanceMetadata> resources) { - this.resources = resources; - } + public void setResources(List<ResourceInstanceMetadata> resources) { + this.resources = resources; + } - public List<ArtifactMetadata> getArtifacts() { - return artifacts; - } + public List<ArtifactMetadata> getArtifacts() { + return artifacts; + } - public void setArtifacts(List<ArtifactMetadata> artifactMetaList) { - this.artifacts = artifactMetaList; - } + public void setArtifacts(List<ArtifactMetadata> artifactMetaList) { + this.artifacts = artifactMetaList; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } - public void setDescription(String description) { - this.description = description; - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java index 2b75facc6c..455e125ffc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java @@ -21,49 +21,49 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ResourceAssetMetadata extends AssetMetadata { - private String category; - private String subCategory; - private String resourceType; - private String lifecycleState; - private String lastUpdaterUserId; + private String category; + private String subCategory; + private String resourceType; + private String lifecycleState; + private String lastUpdaterUserId; - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getSubCategory() { - return subCategory; - } + public String getSubCategory() { + return subCategory; + } - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } - public String getResourceType() { - return resourceType; - } + public String getResourceType() { + return resourceType; + } - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } - public String getLifecycleState() { - return lifecycleState; - } + public String getLifecycleState() { + return lifecycleState; + } - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java index a53422f311..1023f82249 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java @@ -23,67 +23,67 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ResourceInstanceMetadata { - private String resourceInstanceName; - private String resourceName; - private String resourceInvariantUUID; - private String resourceVersion; - private String resoucreType; - private String resourceUUID; - private List<ArtifactMetadata> artifacts; - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(String resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResoucreType() { - return resoucreType; - } - - public void setResoucreType(String resoucreType) { - this.resoucreType = resoucreType; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public List<ArtifactMetadata> getArtifacts() { - return artifacts; - } - - public void setArtifacts(List<ArtifactMetadata> artifacts) { - this.artifacts = artifacts; - } + private String resourceInstanceName; + private String resourceName; + private String resourceInvariantUUID; + private String resourceVersion; + private String resoucreType; + private String resourceUUID; + private List<ArtifactMetadata> artifacts; + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resoucreType; + } + + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List<ArtifactMetadata> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<ArtifactMetadata> artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java index edd88b495d..e677fdc190 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java @@ -23,31 +23,31 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ServiceAssetDetailedMetadata extends ServiceAssetMetadata { - private String lastUpdaterFullName; - private List<ResourceInstanceMetadata> resources; - private List<ArtifactMetadata> artifacts; + private String lastUpdaterFullName; + private List<ResourceInstanceMetadata> resources; + private List<ArtifactMetadata> artifacts; - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } - public List<ResourceInstanceMetadata> getResources() { - return resources; - } + public List<ResourceInstanceMetadata> getResources() { + return resources; + } - public void setResources(List<ResourceInstanceMetadata> resources) { - this.resources = resources; - } + public void setResources(List<ResourceInstanceMetadata> resources) { + this.resources = resources; + } - public List<ArtifactMetadata> getArtifacts() { - return artifacts; - } + public List<ArtifactMetadata> getArtifacts() { + return artifacts; + } - public void setArtifacts(List<ArtifactMetadata> artifacts) { - this.artifacts = artifacts; - } + public void setArtifacts(List<ArtifactMetadata> artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java index 094f973553..6e5ac8426c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java @@ -21,40 +21,40 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ServiceAssetMetadata extends AssetMetadata { - private String category; - private String lifecycleState; - private String lastUpdaterUserId; - private String distributionStatus; - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getLifecycleState() { - return lifecycleState; - } - - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } - - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } - - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } - - public String getDistributionStatus() { - return distributionStatus; - } - - public void setDistributionStatus(String distributionStatus) { - this.distributionStatus = distributionStatus; - } + private String category; + private String lifecycleState; + private String lastUpdaterUserId; + private String distributionStatus; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getDistributionStatus() { + return distributionStatus; + } + + public void setDistributionStatus(String distributionStatus) { + this.distributionStatus = distributionStatus; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java new file mode 100644 index 0000000000..5557c7a609 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.externalapi.servlet.representation; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionReqInfo { + + private String workloadContext; + + public ServiceDistributionReqInfo() { + } + public ServiceDistributionReqInfo(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java new file mode 100644 index 0000000000..3fa54c3654 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.be.externalapi.servlet.representation; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionRespInfo { + + private String distributionId; + + public ServiceDistributionRespInfo() { + } + + public ServiceDistributionRespInfo(String distributionId) { + this.distributionId = distributionId; + } + + public String getDistributionId() { + return distributionId; + } + + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java index de95790f4e..841cd3225d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java @@ -20,27 +20,15 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.StringTokenizer; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ConsumerDefinition; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.openecomp.sdc.security.Passwords; @@ -48,178 +36,186 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.StringTokenizer; @Priority(10) public class BasicAuthenticationFilter implements ContainerRequestFilter { - @Context - private HttpServletRequest sr; - - protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - private String realm = "ASDC"; - - private static Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER); - if (authHeader != null) { - StringTokenizer st = new StringTokenizer(authHeader); - if (st.hasMoreTokens()) { - String basic = st.nextToken(); - - if (basic.equalsIgnoreCase("Basic")) { - try { - String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); - log.debug("Credentials: {}" , credentials); - checkUserCredentiles(requestContext, credentials); - } catch (UnsupportedEncodingException e) { - log.error("Authentication Filter Failed Couldn't retrieve authentication", e); - authInvalidHeaderError(requestContext); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - } - - } else { - log.error("Authentication Filter Failed no autharization header"); - authRequiredError(requestContext); - } - } - - private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) { - int p = credentials.indexOf(":"); - if (p != -1) { - String _username = credentials.substring(0, p).trim(); - String _password = credentials.substring(p + 1).trim(); - - ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic(); - if (consumerBL == null) { - log.error("Authentication Filter Failed to get consumerBL."); - requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); - } else { - Either<ConsumerDefinition, ResponseFormat> result = consumerBL.getConsumer(_username); - validatePassword(requestContext, _username, _password, result); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - - } - } - - private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either<ConsumerDefinition, ResponseFormat> result) { - if (result.isRight()) { - Integer status = result.right().value().getStatus(); - if (status == Status.NOT_FOUND.getStatusCode()) { - log.error("Authentication Filter Failed Couldn't find user"); - authUserNotFoundError(requestContext, _username); - } else { - log.error("Authentication Filter Failed to get consumerBL."); - requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); - } - } else { - ConsumerDefinition consumerCredentials = result.left().value(); - if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) { - log.error("Authentication Filter Failed invalide password"); - authInvalidePasswordError(requestContext, _username); - } else { - authSuccesessful(requestContext, _username); - } - } - } - - private void authSuccesessful(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm); - } - - private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authInvalidHeaderError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authRequiredError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED); - requestContext.abortWith(buildErrorResponse(responseFormat, true)); - } - - private ComponentsUtils getComponentsUtils() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - private ConsumerBusinessLogic getConsumerBusinessLogic() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class); - return consumerBusinessLogic; - } - - public enum AuthStatus { - AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS - } - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) { - ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus()); - if (addWwwAuthenticationHeader) { - responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\""); - } - Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; - } + @Context + private HttpServletRequest sr; + + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + private String realm = "ASDC"; + + private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + + String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER); + if (authHeader != null) { + StringTokenizer st = new StringTokenizer(authHeader); + if (st.hasMoreTokens()) { + String basic = st.nextToken(); + + if (basic.equalsIgnoreCase("Basic")) { + try { + String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); + log.debug("Credentials: {}" , credentials); + checkUserCredentiles(requestContext, credentials); + } catch (UnsupportedEncodingException e) { + log.error("Authentication Filter Failed Couldn't retrieve authentication", e); + authInvalidHeaderError(requestContext); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + } + + } else { + log.error("Authentication Filter Failed no autharization header"); + authRequiredError(requestContext); + } + } + + private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) { + int p = credentials.indexOf(":"); + if (p != -1) { + String _username = credentials.substring(0, p).trim(); + String _password = credentials.substring(p + 1).trim(); + + ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic(); + if (consumerBL == null) { + log.error("Authentication Filter Failed to get consumerBL."); + requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); + } else { + Either<ConsumerDefinition, ResponseFormat> result = consumerBL.getConsumer(_username); + validatePassword(requestContext, _username, _password, result); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + + } + } + + private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either<ConsumerDefinition, ResponseFormat> result) { + if (result.isRight()) { + Integer status = result.right().value().getStatus(); + if (status == Status.NOT_FOUND.getStatusCode()) { + log.error("Authentication Filter Failed Couldn't find user"); + authUserNotFoundError(requestContext, _username); + } else { + log.error("Authentication Filter Failed to get consumerBL."); + requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); + } + } else { + ConsumerDefinition consumerCredentials = result.left().value(); + if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) { + log.error("Authentication Filter Failed invalide password"); + authInvalidePasswordError(requestContext, _username); + } else { + authSuccesessful(requestContext, _username); + } + } + } + + private void authSuccesessful(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm); + } + + private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authInvalidHeaderError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authRequiredError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED); + requestContext.abortWith(buildErrorResponse(responseFormat, true)); + } + + private ComponentsUtils getComponentsUtils() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); + return componentsUtils; + } + + private ConsumerBusinessLogic getConsumerBusinessLogic() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class); + return consumerBusinessLogic; + } + + public enum AuthStatus { + AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS + } + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) { + ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus()); + if (addWwwAuthenticationHeader) { + responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\""); + } + Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java index d24743534c..60409b3ee0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java @@ -20,20 +20,7 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.util.UUID; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - +import com.google.gson.GsonBuilder; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -50,171 +37,180 @@ import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.GsonBuilder; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.util.UUID; @Provider @Priority(1) public class BeServletFilter implements ContainerRequestFilter, ContainerResponseFilter { - @Context - private HttpServletRequest sr; - - private static Logger log = LoggerFactory.getLogger(BeServletFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - try { - - MDC.clear(); - - // In case of 405 response code, this function is not entered, then - // we'll process - // the MDC fields and UUID during the response - ThreadLocalsHolder.setMdcProcessed(true); - - // Timing HTTP request - ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); - - String uuid = processMdcFields(requestContext); - - ThreadLocalsHolder.setUuid(uuid); - - inHttpRequest(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during request filter: {} ", e); - } - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - try { - // Formatting the response in case of 405 - if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); - responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); - } - - if (ThreadLocalsHolder.isMdcProcessed()) { - // filter() was executed during request - this is the regular - // flow - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); - Long startTime = ThreadLocalsHolder.getRequestStartTime(); - if (startTime != null) { - long endTime = System.currentTimeMillis(); - MDC.put("timer", Long.toString(endTime - startTime)); - } - } else { - // this is the 405 response code case - // we have no MDC fields since filter() wasn't executed during - // request - String uuid = processMdcFields(requestContext); - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid); - } - - outHttpResponse(responseContext); - - log.debug("Close transaction from filter"); - TitanDao titanDao = getTitanDao(); - if ( titanDao != null ){ - if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){ - titanDao.commit(); - log.debug("Doing commit from filter"); - }else{ - titanDao.rollback(); - log.debug("Doing rollback from filter"); - } - } - // Cleaning up - MDC.clear(); - ThreadLocalsHolder.cleanup(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during response filter: {} ", e); - } - } - - private String processMdcFields(ContainerRequestContext requestContext) { - // UserId for logging - String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); - MDC.put("userId", userId); - - String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER); - MDC.put("serviceInstanceID", serviceInstanceID); - - MDC.put("remoteAddr", sr.getRemoteAddr()); - MDC.put("localAddr", sr.getLocalAddr()); - - // UUID - String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER); - if (uuid == null) { - // Generate the UUID - uuid = UUID.randomUUID().toString(); - - // Add to MDC for logging - MDC.put("uuid", uuid); - - // This log message should already be with the UUID - uuidGeneration(uuid); - - } else { - // According to Ella, in case this header exists, we don't have to - // perform any validations - // since it's not our responsibilty, so we log the UUID just as it - // was received. - MDC.put("uuid", uuid); - } - return uuid; - } - - private ComponentsUtils getComponentsUtils() { - ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(ComponentsUtils.class); - } - private TitanDao getTitanDao() { - ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(TitanDao.class); - } - // Extracted for purpose of clear method name, for logback %M parameter - private void inHttpRequest() { - if (isInfoLog()) { - log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } else { - log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void outHttpResponse(ContainerResponseContext responseContext) { - if (isInfoLog()) { - log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } else { - log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } - } - - private boolean isInfoLog() { - boolean logRequest = true; - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - String requestURI = sr.getRequestURI(); - if (requestURI != null && configuration.getUnLoggedUrls() != null) { - logRequest = !configuration.getUnLoggedUrls().contains(requestURI); - } - - return logRequest; - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void uuidGeneration(String uuid) { - log.info("No requestID provided -> Generated UUID {}", uuid); - } + @Context + private HttpServletRequest sr; + + private static final Logger log = LoggerFactory.getLogger(BeServletFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + try { + + MDC.clear(); + + // In case of 405 response code, this function is not entered, then + // we'll process + // the MDC fields and UUID during the response + ThreadLocalsHolder.setMdcProcessed(true); + + // Timing HTTP request + ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); + + String uuid = processMdcFields(requestContext); + + ThreadLocalsHolder.setUuid(uuid); + + inHttpRequest(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during request filter: {} ", e); + } + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + try { + // Formatting the response in case of 405 + if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); + responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); + } + + if (ThreadLocalsHolder.isMdcProcessed()) { + // filter() was executed during request - this is the regular + // flow + responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); + Long startTime = ThreadLocalsHolder.getRequestStartTime(); + if (startTime != null) { + long endTime = System.currentTimeMillis(); + MDC.put("timer", Long.toString(endTime - startTime)); + } + } else { + // this is the 405 response code case + // we have no MDC fields since filter() wasn't executed during + // request + String uuid = processMdcFields(requestContext); + responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid); + } + + outHttpResponse(responseContext); + + log.debug("Close transaction from filter"); + TitanDao titanDao = getTitanDao(); + if ( titanDao != null ){ + if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){ + titanDao.commit(); + log.debug("Doing commit from filter"); + }else{ + titanDao.rollback(); + log.debug("Doing rollback from filter"); + } + } + // Cleaning up + MDC.clear(); + ThreadLocalsHolder.cleanup(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during response filter: {} ", e); + } + } + + private String processMdcFields(ContainerRequestContext requestContext) { + // UserId for logging + String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); + MDC.put("userId", userId); + + String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER); + MDC.put("serviceInstanceID", serviceInstanceID); + + MDC.put("remoteAddr", sr.getRemoteAddr()); + MDC.put("localAddr", sr.getLocalAddr()); + + // UUID + String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER); + if (uuid == null) { + // Generate the UUID + uuid = UUID.randomUUID().toString(); + + // Add to MDC for logging + MDC.put("uuid", uuid); + + // This log message should already be with the UUID + uuidGeneration(uuid); + + } else { + // According to Ella, in case this header exists, we don't have to + // perform any validations + // since it's not our responsibilty, so we log the UUID just as it + // was received. + MDC.put("uuid", uuid); + } + return uuid; + } + + private ComponentsUtils getComponentsUtils() { + ServletContext context = this.sr.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentsUtils.class); + } + private TitanDao getTitanDao() { + ServletContext context = this.sr.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(TitanDao.class); + } + // Extracted for purpose of clear method name, for logback %M parameter + private void inHttpRequest() { + if (isInfoLog()) { + log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); + } else { + log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); + } + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void outHttpResponse(ContainerResponseContext responseContext) { + if (isInfoLog()) { + log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); + } else { + log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); + } + } + + private boolean isInfoLog() { + boolean logRequest = true; + Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); + String requestURI = sr.getRequestURI(); + if (requestURI != null && configuration.getUnLoggedUrls() != null) { + logRequest = !configuration.getUnLoggedUrls().contains(requestURI); + } + + return logRequest; + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void uuidGeneration(String uuid) { + log.info("No requestID provided -> Generated UUID {}", uuid); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java index c572e2e552..b80ee4c324 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java @@ -20,21 +20,9 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -46,77 +34,87 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; @Priority(11) public class ComponentsAvailabilityFilter implements ContainerRequestFilter { - @Context - protected HttpServletRequest sr; - protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - String requestUrl = requestContext.getUriInfo().getPath(); - if (!requestUrl.equals("healthCheck")) { - List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext()); - ActionStatus status = getAggregateBeStatus(beHealthCheckInfos); - - if (!status.equals(ActionStatus.OK)) { - log.error("Components Availability Filter Failed - ES/Cassandra is DOWN"); - availabilityError(requestContext); - } - } - - } - - protected ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) { - ActionStatus status = ActionStatus.OK; - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { - status = ActionStatus.GENERAL_ERROR; - break; - } - } - return status; - } - - protected List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) { - - List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>(); - HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); - healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan - return healthCheckInfos; - } - - protected ComponentsUtils getComponentsUtils() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - protected void availabilityError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Components Availability Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus()); - Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build(); - requestContext.abortWith(response); - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } + @Context + protected HttpServletRequest sr; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + + String requestUrl = requestContext.getUriInfo().getPath(); + if (!requestUrl.equals("healthCheck")) { + List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext()); + ActionStatus status = getAggregateBeStatus(beHealthCheckInfos); + + if (!status.equals(ActionStatus.OK)) { + log.error("Components Availability Filter Failed - ES/Cassandra is DOWN"); + availabilityError(requestContext); + } + } + + } + + protected ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) { + ActionStatus status = ActionStatus.OK; + for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { + if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { + status = ActionStatus.GENERAL_ERROR; + break; + } + } + return status; + } + + protected List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) { + + List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>(); + HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); + healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan + return healthCheckInfos; + } + + protected ComponentsUtils getComponentsUtils() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); + return componentsUtils; + } + + protected void availabilityError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Components Availability Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus()); + Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build(); + requestContext.abortWith(response); + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index 910521c8dc..566daec5e7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -20,23 +20,24 @@ package org.openecomp.sdc.be.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; - -import org.codehaus.jackson.Version; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.JsonDeserializer; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.module.SimpleModule; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditConsumerEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditResourceEventFactoryMananger; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.auditing.impl.distribution.AuditDistribDownloadEventFactory; +import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAccessEventFactory; +import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAdminEventFactory; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -46,7 +47,6 @@ import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ConsumerDefinition; @@ -56,12 +56,14 @@ import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.ToscaError; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -71,1451 +73,1370 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component("componentUtils") public class ComponentsUtils { - @javax.annotation.Resource - private IAuditingManager auditingManager; - - private ResponseFormatManager responseFormatManager; - - private static Logger log = LoggerFactory.getLogger(ComponentsUtils.class.getName()); - - @PostConstruct - public void Init() { - this.responseFormatManager = ResponseFormatManager.getInstance(); - } - - public IAuditingManager getAuditingManager() { - return auditingManager; - } - - public void setAuditingManager(IAuditingManager auditingManager) { - this.auditingManager = auditingManager; - } - - public <T> Either<T, ResponseFormat> convertJsonToObject(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum) { - if (data == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - try { - T obj = parseJsonToObject(data, clazz); - return Either.left(obj); - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - } - - public static <T> T parseJsonToObject(String data, Class<T> clazz) { - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - log.trace("convert json to object. json=\n{}", data); - T resource = gson.fromJson(data, clazz); - return resource; - } - - public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { - T component = null; - ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - try { - log.trace("convert json to object. json=\n{}", data); - - final SimpleModule module = new SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static version")); - JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); - addDeserializer(module, PropertyConstraint.class, desrializer); - // - mapper.registerModule(module); - - component = mapper.readValue(data, clazz); - if (component == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); - return Either.right(responseFormat); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); - return Either.right(responseFormat); - } - return Either.left(component); - } - - public <T> void addDeserializer(SimpleModule module, Class<T> clazz, final JsonDeserializer<T> deserializer) { - module.addDeserializer(clazz, deserializer); - } - - // Error response - - public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) { - return responseFormatManager.getResponseFormat(actionStatus, params); - } - - public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) { - return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params); - } - - /** - * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he - * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields. - * - * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service. - * - * @param actionStatus - * @param resource - * @return - */ - public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) { - if (resource == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case COMPONENT_VERSION_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion()); - break; - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName()); - break; - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - break; - case COMPONENT_IN_USE: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) { - if (resourceName == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) { - if (capabilityType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case CAPABILITY_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public <T> ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) { - if (obj == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat = null; - - switch (actionStatus) { - case MISSING_CAPABILITY_TYPE: - if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List<?>) obj)){ - List<?> list = (List<?>)obj; - if ( list.get(0) instanceof RequirementDefinition ) { - responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object - return responseFormat; - } - } - log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>"); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - /** - * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he - * received. It's caller's responisibility to fill the passed resource object with needed fields. - * - * @param actionStatus - * @param user - * @return - */ - public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) { - if (user == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat requestErrorWrapper; - switch (actionStatus) { - case INVALID_USER_ID: - requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); - break; - case INVALID_EMAIL_ADDRESS: - requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail()); - break; - case INVALID_ROLE: - requestErrorWrapper = getResponseFormat(actionStatus, user.getRole()); - break; - case USER_NOT_FOUND: - case USER_ALREADY_EXIST: - case USER_INACTIVE: - case USER_HAS_ACTIVE_ELEMENTS: - requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); - break; - default: - requestErrorWrapper = getResponseFormat(actionStatus); - break; - } - return requestErrorWrapper; - } - - public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) { - User user = new User(); - user.setUserId(userId); - return getResponseFormatByUser(actionStatus, user); - } - - public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName); - break; - case DISTRIBUTION_ENVIRONMENT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName); - break; - case DISTRIBUTION_ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_NOT_FOUND: - case ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) { - ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("audit before sending response"); - auditResource(responseFormat, user, null, "", "", actionEnum, null); - return responseFormat; - } - - public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { - ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("audit before sending response"); - auditComponentAdmin(responseFormat, user, null, "", "", actionEnum, typeEnum); - return responseFormat; - } - - public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String prevState, String prevVersion, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - if (actionEnum != null) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - updateUserFields(modifier, auditingFields); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState); - if (resource != null) { - // fields that are filled during creation and might still be - // empty - String resourceCurrVersion = (resource.getVersion() != null) ? resource.getVersion() : ""; - String resourceCurrState = (resource.getLifecycleState() != null) ? resource.getLifecycleState().name() : ""; - String uuid = (resource.getUUID() != null) ? resource.getUUID() : ""; - String invariantUUID = (resource.getInvariantUUID() != null) ? resource.getInvariantUUID() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID); - - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // In those specific cases we want some specific fields from - // resource object - switch (actionEnum) { - case IMPORT_RESOURCE: - if (resource != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, resource.getToscaResourceName()); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); - } - break; - default: - break; - } - - // This is to add/overwrite anything set in this function if some - // params were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - } - - private void updateUserFields(User modifier, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { - if (modifier != null) { - String firstName = modifier.getFirstName(); - String lastName = modifier.getLastName(); - if (firstName != null || lastName != null) {// to prevent "null - // null" names - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - } - - public void auditDistributionDownload(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // This is to add/overwrite anything set in this function if some params - // were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum); - String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); - String requestURI = request.getRequestURI(); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - int status = 0; - String message = ""; - if(responseFormat != null){ - status = responseFormat.getStatus(); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - if(!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)){ - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - } - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); - } - - public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); - } - - public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); - } - - public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); - } - - public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - updateUserFields(modifier, auditingFields); - // String componentTypeStr = (componentTypeEnum != null ? - // componentTypeEnum.getValue() : null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName); - getAuditingManager().auditEvent(auditingFields); - } - - public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) { - - return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE); - } - - public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) { - - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - if (storageResponse == null) { - return responseEnum; - } - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; - break; - case PARENT_RESOURCE_NOT_FOUND: - responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND; - break; - case MULTIPLE_PARENT_RESOURCE_FOUND: - responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND; - break; - case NOT_FOUND: - if (ComponentTypeEnum.RESOURCE == type) { - responseEnum = ActionStatus.RESOURCE_NOT_FOUND; - } else if (ComponentTypeEnum.PRODUCT == type) { - responseEnum = ActionStatus.PRODUCT_NOT_FOUND; - } else { - responseEnum = ActionStatus.SERVICE_NOT_FOUND; - } - break; - case FAILED_TO_LOCK_ELEMENT: - responseEnum = ActionStatus.COMPONENT_IN_USE; - break; - case ARTIFACT_NOT_FOUND: - responseEnum = ActionStatus.ARTIFACT_NOT_FOUND; - break; - case DISTR_ENVIRONMENT_NOT_AVAILABLE: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE; - break; - case DISTR_ENVIRONMENT_NOT_FOUND: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND; - break; - case DISTR_ENVIRONMENT_SENT_IS_INVALID: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID; - break; - case DISTR_ARTIFACT_NOT_FOUND: - responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND; - break; - case INVALID_TYPE: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case INVALID_VALUE: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case CSAR_NOT_FOUND: - responseEnum = ActionStatus.CSAR_NOT_FOUND; - break; - case PROPERTY_NAME_ALREADY_EXISTS: - responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY; - break; - case CATEGORY_NOT_FOUND: - responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; - break; - case INVALID_PROPERTY: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromToscaError(ToscaError toscaError) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - if (toscaError == null) { - return responseEnum; - } - switch (toscaError) {// TODO match errors - case NODE_TYPE_CAPABILITY_ERROR: - case NOT_SUPPORTED_TOSCA_TYPE: - case NODE_TYPE_REQUIREMENT_ERROR: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case INVALID_ID: - responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; - break; - case INVALID_PROPERTY: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; - break; - case NOT_FOUND: - if (isRelation) { - responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND; - } else { - responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; - } - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_INSTANCE_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - break; - default: - responseFormat = getResponseFormat(actionStatus, serviceName); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_INSTANCE_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case INVALID_ID: - responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; - break; - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; - break; - case NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type) { - auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type, null); - } - - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { - if (actionEnum != null) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - updateUserFields(modifier, auditingFields); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, type.getValue().replace(" ", "")); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState); - if (component != null) { - // fields that are filled during creation and might still be - // empty - String resourceCurrVersion = component.getVersion(); - String resourceCurrState = (component.getLifecycleState() != null) ? component.getLifecycleState().name() : ""; - String resourceUuid = (component.getUUID() != null) ? component.getUUID() : ""; - String invariantUUID = (component.getInvariantUUID() != null) ? component.getInvariantUUID() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resourceUuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // This is meant to overwrite anything set in this function if some - // params were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - } - - public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState, - String topicName, String distributionId, String description, String status) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); - - // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - // environmentName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditAuthEvent(AuditingActionEnum actionEnum, String url, String user, String authStatus, String realm) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, url); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, user); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, authStatus); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, realm); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId); - ThreadLocalsHolder.setUuid(distributionId); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) { - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - StringBuilder ecompUser = new StringBuilder(); - if (consumer != null) { - if (consumer.getConsumerName() != null && !consumer.getConsumerName().trim().isEmpty()) { - ecompUser.append(consumer.getConsumerName()); - } - if (consumer.getConsumerSalt() != null && !consumer.getConsumerSalt().trim().isEmpty()) { - if (ecompUser.length() > 0) { - ecompUser.append(","); - } - ecompUser.append(consumer.getConsumerSalt()); - } - if (consumer.getConsumerPassword() != null && !consumer.getConsumerPassword().trim().isEmpty()) { - if (ecompUser.length() > 0) { - ecompUser.append(","); - } - ecompUser.append(consumer.getConsumerPassword()); - } - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, ecompUser.toString()); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, ""); - } - if (userBefore != null) { - String userBeforeUserId = (userBefore.getUserId() != null) ? userBefore.getUserId() : ""; - String userBeforFirstName = (userBefore.getFirstName() != null) ? ", " + userBefore.getFirstName() + " " : ""; - String userBeforLastName = (userBefore.getLastName() != null) ? userBefore.getLastName() : ""; - String userBeforEmail = (userBefore.getEmail() != null) ? ", " + userBefore.getEmail() : ""; - String userBeforRloe = (userBefore.getRole() != null) ? ", " + userBefore.getRole() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, userBeforeUserId + userBeforFirstName + userBeforLastName + userBeforEmail + userBeforRloe); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, ""); - } - if (userAfter != null) { - String userAfterUserId = (userAfter.getUserId() != null) ? userAfter.getUserId() : ""; - String userAfterFirstName = (userAfter.getFirstName() != null) ? ", " + userAfter.getFirstName() + " " : ""; - String userAfterLastName = (userAfter.getLastName() != null) ? userAfter.getLastName() : ""; - String userAfterEmail = (userAfter.getEmail() != null) ? ", " + userAfter.getEmail() : ""; - String userAfterRloe = (userAfter.getRole() != null) ? ", " + userAfter.getRole() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, userAfterUserId + userAfterFirstName + userAfterLastName + userAfterEmail + userAfterRloe); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, ""); - } - - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')'); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { - - EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) { - if (component == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case COMPONENT_VERSION_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion()); - break; - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - case COMPONENT_IN_USE: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId()); - break; - case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public Either<Boolean, ResponseFormat> validateStringNotEmpty(User user, Component component, String value, ActionStatus badResult, AuditingActionEnum actionEnum) { - if ((value == null) || (value.trim().isEmpty())) { - log.info(badResult.name()); - ResponseFormat errorResponse = getResponseFormat(badResult); - if (actionEnum != null) { - log.debug("audit before sending response"); - auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component)); - } - return Either.right(errorResponse); - } - return Either.left(true); - } - - public Boolean validateStringNotEmpty(String value) { - if ((value == null) || (value.trim().isEmpty())) { - return false; - } - return true; - } - - private ComponentTypeEnum getComponentType(Component component) { - if (component instanceof Service) { - return ComponentTypeEnum.SERVICE; - } // else if(component instanceof Resource){ - return null; - } - - public Either<Boolean, ResponseFormat> validateStringMatchesPattern(User user, Component component, String value, Pattern pattern, ActionStatus badResult, AuditingActionEnum actionEnum) { - if (!pattern.matcher(value).matches()) { - log.error(badResult.name()); - ResponseFormat errorResponse = getResponseFormat(badResult); - if (actionEnum != null) { - log.debug("audit before sending response"); - auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component)); - } - return Either.right(errorResponse); - } - return Either.left(true); - } - - /** - * - * " Error: Missing Mandatory Informational %s1 %s2 : %s3 " where %s1 - "resource"/"service" %s2 - "artifact"/ "artifacts" %s3 - Comma separated list of missing informational artifact types - * - * @param resource - * @param componentMissingMandatoryArtifacts - * @param value - * @return - */ - public ResponseFormat getResponseFormatByMissingArtifacts(ComponentTypeEnum componentType, Map<String, ArtifactDefinition> artifacts) { - - String artifactTitle = "artifact"; - if (artifacts.size() > 1) { - artifactTitle = "artifacts"; - } - Collection<ArtifactDefinition> artifactsLabels = artifacts.values(); - StringBuilder artifactsLabelBuilder = new StringBuilder(); - - List<ArtifactDefinition> artifactsLabelsList = new ArrayList<ArtifactDefinition>(); - artifactsLabelsList.addAll(artifactsLabels); - for (int i = 0; i < artifactsLabelsList.size(); i++) { - ArtifactDefinition artifactDef = artifactsLabelsList.get(i); - artifactsLabelBuilder.append(artifactDef.getArtifactDisplayName()); - if (i < artifactsLabelsList.size() - 1) { - artifactsLabelBuilder.append(";"); - } - } - ResponseFormat responseFormat = getResponseFormat(ActionStatus.COMPONENT_MISSING_MANDATORY_ARTIFACTS, componentType.name().toLowerCase(), artifactTitle, artifactsLabelBuilder.toString()); - - return responseFormat; - } - - public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; - break; - case INVALID_ID: - responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - switch (resultStatus) { - case OK: - responseEnum = ActionStatus.OK; - break; - case ELEMENT_NOT_FOUND: - if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ - responseEnum = ActionStatus.PROPERTY_NOT_FOUND; - } - break; - case INVALID_PROPERTY_DEFAULT_VALUE: - case INVALID_PROPERTY_TYPE: - case INVALID_PROPERTY_VALUE: - case INVALID_PROPERTY_NAME: - case MISSING_ENTRY_SCHEMA_TYPE: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - return responseEnum; - } - - public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { - - if (additionalInfoParameterInfo == null) { - additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - } - if (labelOrValue == null) { - labelOrValue = AdditionalInformationEnum.None; - } - - ResponseFormat responseFormat = null; - switch (actionStatus) { - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey()); - break; - case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: - responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); - break; - case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: - responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase()); - break; - case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - - return responseFormat; - } - - public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) { - return getResponseFormatAdditionalProperty(actionStatus, null, null, null); - } - - public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; - break; - case NOT_FOUND: - responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; - break; - case CANNOT_UPDATE_EXISTING_ENTITY: - responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) { - if (groupType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case GROUP_MEMBER_EMPTY: - case GROUP_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, groupType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - - } - - public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) { - if (policyType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case POLICY_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, policyType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - - } - - public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) { - if (dataType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case DATA_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: - responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); - break; - case DATA_TYPE_DERIVED_IS_MISSING: - responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName()); - break; - case DATA_TYPE_DUPLICATE_PROPERTY: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: - responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); - break; - case DATA_TYPE_CANNOT_HAVE_PROPERTIES: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } + private static final Logger log = LoggerFactory.getLogger(ComponentsUtils.class); + private final AuditingManager auditingManager; + private final ResponseFormatManager responseFormatManager; + + public ComponentsUtils(AuditingManager auditingManager) { + this.auditingManager = auditingManager; + this.responseFormatManager = ResponseFormatManager.getInstance(); + } + + public AuditingManager getAuditingManager() { + return auditingManager; + } + + public <T> Either<T, ResponseFormat> convertJsonToObject(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum) { + if (data == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); + return Either.right(responseFormat); + } + try { + T obj = parseJsonToObject(data, clazz); + return Either.left(obj); + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); + return Either.right(responseFormat); + } + } + + public static <T> T parseJsonToObject(String data, Class<T> clazz) { + Type constraintType = new TypeToken<PropertyConstraint>() {}.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + log.trace("convert json to object. json=\n{}", data); + return gson.fromJson(data, clazz); + } + + public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { + T component = null; + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + try { + log.trace("convert json to object. json=\n{}", data); + + SimpleModule module = new SimpleModule("customDeserializationModule"); + module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer()); + mapper.registerModule(module); + + component = mapper.readValue(data, clazz); + if (component == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); + return Either.right(responseFormat); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); + return Either.right(responseFormat); + } + return Either.left(component); + } + + public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) { + return responseFormatManager.getResponseFormat(actionStatus, params); + } + + public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) { + return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params); + } + + public <T> Either<List<T>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) { + return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) : + Either.right(getResponseFormat(storageOperationStatus)); + } + + /** + * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he + * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields. + * <p> + * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service. + * + * @param actionStatus + * @param resource + * @return + */ + public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) { + if (resource == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case COMPONENT_VERSION_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion()); + break; + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName()); + break; + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + break; + case COMPONENT_IN_USE: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) { + if (resourceName == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) { + if (capabilityType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case CAPABILITY_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public <T> ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) { + if (obj == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat = null; + + switch (actionStatus) { + case MISSING_CAPABILITY_TYPE: + if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)) { + List list = (List) obj; + if (list.get(0) instanceof RequirementDefinition) { + responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object + return responseFormat; + } + } + log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>"); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + /** + * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he + * received. It's caller's responisibility to fill the passed resource object with needed fields. + * + * @param actionStatus + * @param user + * @return + */ + public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) { + if (user == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat requestErrorWrapper; + switch (actionStatus) { + case INVALID_USER_ID: + requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); + break; + case INVALID_EMAIL_ADDRESS: + requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail()); + break; + case INVALID_ROLE: + requestErrorWrapper = getResponseFormat(actionStatus, user.getRole()); + break; + case USER_NOT_FOUND: + case USER_ALREADY_EXIST: + case USER_INACTIVE: + case USER_HAS_ACTIVE_ELEMENTS: + requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); + break; + default: + requestErrorWrapper = getResponseFormat(actionStatus); + break; + } + return requestErrorWrapper; + } + + public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) { + User user = new User(); + user.setUserId(userId); + return getResponseFormatByUser(actionStatus, user); + } + + public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) { + ResponseFormat responseFormat; + + switch (actionStatus) { + case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName); + break; + case DISTRIBUTION_ENVIRONMENT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName); + break; + case DISTRIBUTION_ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) { + ResponseFormat responseFormat; + + switch (actionStatus) { + case RESOURCE_NOT_FOUND: + case ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAudit(User user, String resourceName, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditResource(responseFormat, user, resourceName, actionEnum); + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditAdminUserAction(actionEnum, user, null, null, responseFormat); + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum); + return responseFormat; + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceAuditData prevResFields) { + auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, String resourceName, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, null, resourceName, actionEnum); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, resource, resourceName, actionEnum, ResourceAuditData.newBuilder().build(), null, null); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum, + ResourceAuditData prevResFields, String currentArtifactUuid, String artifactData) { + if (actionEnum != null) { + int status = responseFormat.getStatus(); + String message = ""; + String uuid = null; + String resourceCurrVersion = null; + String resourceCurrState = null; + String invariantUUID = null; + String resourceType = ComponentTypeEnum.RESOURCE.getValue(); + String toscaNodeType = null; + + log.trace("Inside auditing for audit action {}", actionEnum); + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + if (resource != null) { + resourceName = resource.getName(); + resourceCurrVersion = resource.getVersion(); + if (resource.getLifecycleState() != null) { + resourceCurrState = resource.getLifecycleState().name(); + } + if (resource.getResourceType() != null) { + resourceType = resource.getResourceType().name(); + } + invariantUUID = resource.getInvariantUUID(); + uuid = resource.getUUID(); + toscaNodeType = resource.getToscaResourceName(); + } + + AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory( + actionEnum, + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .serviceInstanceId(uuid) + .build(), + prevResFields, + ResourceAuditData.newBuilder() + .artifactUuid(currentArtifactUuid) + .state(resourceCurrState) + .version(resourceCurrVersion) + .build(), + resourceType, resourceName, invariantUUID, + modifier, artifactData, null, null, toscaNodeType); + + getAuditingManager().auditEvent(factory); + } + } + + private void updateUserFields(User modifier, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) { + if (modifier != null) { + String firstName = modifier.getFirstName(); + String lastName = modifier.getLastName(); + if (firstName != null || lastName != null) {// to prevent "null + // null" names + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + } + + public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) { + log.trace("Inside auditing"); + int status = responseFormat.getStatus(); + String message = ""; + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + getAuditingManager().auditEvent(auditingFields); + AuditDistribDownloadEventFactory factory = new AuditDistribDownloadEventFactory( + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + distributionData); + getAuditingManager().auditEvent(factory); + } + + public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + log.trace("Inside auditing for audit action {}", actionEnum); + int status = responseFormat.getStatus(); + String message = ""; + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + if (additionalParams != null) { + auditingFields.putAll(additionalParams); + } + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + log.trace("Inside auditing for audit action {}", actionEnum); + String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); + String requestURI = request.getRequestURI(); + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + int status = 0; + String message = ""; + if (responseFormat != null) { + status = responseFormat.getStatus(); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + if (additionalParams != null) { + auditingFields.putAll(additionalParams); + if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + } + } + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditExternalActivateService(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName(), request, additionalParams); + }public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); + } + + public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); + } + + public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); + } + + public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); + } + + public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { + log.trace("Inside auditing for audit action {}", actionEnum); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + updateUserFields(modifier, auditingFields); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName); + getAuditingManager().auditEvent(auditingFields); + } + + public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) { + + return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE); + } + + public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) { + + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + if (storageResponse == null) { + return responseEnum; + } + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; + break; + case PARENT_RESOURCE_NOT_FOUND: + responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND; + break; + case MULTIPLE_PARENT_RESOURCE_FOUND: + responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND; + break; + case NOT_FOUND: + if (ComponentTypeEnum.RESOURCE == type) { + responseEnum = ActionStatus.RESOURCE_NOT_FOUND; + } else if (ComponentTypeEnum.PRODUCT == type) { + responseEnum = ActionStatus.PRODUCT_NOT_FOUND; + } else { + responseEnum = ActionStatus.SERVICE_NOT_FOUND; + } + break; + case FAILED_TO_LOCK_ELEMENT: + responseEnum = ActionStatus.COMPONENT_IN_USE; + break; + case ARTIFACT_NOT_FOUND: + responseEnum = ActionStatus.ARTIFACT_NOT_FOUND; + break; + case DISTR_ENVIRONMENT_NOT_AVAILABLE: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE; + break; + case DISTR_ENVIRONMENT_NOT_FOUND: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND; + break; + case DISTR_ENVIRONMENT_SENT_IS_INVALID: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID; + break; + case DISTR_ARTIFACT_NOT_FOUND: + responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND; + break; + case INVALID_TYPE: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case INVALID_VALUE: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case CSAR_NOT_FOUND: + responseEnum = ActionStatus.CSAR_NOT_FOUND; + break; + case PROPERTY_NAME_ALREADY_EXISTS: + responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY; + break; + case CATEGORY_NOT_FOUND: + responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; + break; + case INVALID_PROPERTY: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromToscaError(ToscaError toscaError) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + if (toscaError == null) { + return responseEnum; + } + switch (toscaError) {// TODO match errors + case NODE_TYPE_CAPABILITY_ERROR: + case NOT_SUPPORTED_TOSCA_TYPE: + case NODE_TYPE_REQUIREMENT_ERROR: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case INVALID_ID: + responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; + break; + case INVALID_PROPERTY: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; + break; + case NOT_FOUND: + if (isRelation) { + responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND; + } else { + responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; + } + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) { + ResponseFormat responseFormat; + + if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { + responseFormat = getResponseFormat(actionStatus, resourceInstanceName); + } + else { + responseFormat = getResponseFormat(actionStatus, serviceName); + } + return responseFormat; + } + + public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) { + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { + responseFormat = getResponseFormat(actionStatus, resourceInstanceName); + } + else { + responseFormat = getResponseFormat(actionStatus); + } + return responseFormat; + } + + public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case INVALID_ID: + responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; + break; + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; + break; + case NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, String comment) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, comment, null, null); + } + + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) { + auditComponent(responseFormat, modifier, component, actionEnum, type, ResourceAuditData.newBuilder().build()); + } + + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, null, null, null); + } + + + public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, String compName, ComponentTypeEnum type, String comment) { + auditComponent(responseFormat, modifier, null, actionEnum, type, ResourceAuditData.newBuilder().build(), null, compName, comment, null, null); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, currComponent, null, null, null, null); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent, String compName, String comment, String artifactData, String did) { + if (actionEnum != null) { + String uuid = null; + String currState = null; + String invariantUUID = null; + String currArtifactUid = null; + String currVersion = null; + String dcurrStatus = null; + String message = ""; + + int status = responseFormat.getStatus(); + + log.trace("Inside auditing for audit action {}", actionEnum); + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + + if (component != null) { + // fields that are filled during creation and might still be empty + if (component.getLifecycleState() != null) { + currState = component.getLifecycleState().name(); + } + uuid = component.getUUID(); + invariantUUID = component.getInvariantUUID(); + currVersion = component.getVersion(); + if (StringUtils.isEmpty(compName)) { + compName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + } + } + if (currComponent != null) { + currArtifactUid = currComponent.getArtifactUuid(); + dcurrStatus = currComponent.getDistributionStatus(); + if (currState == null) { //probably it was not set + currState = currComponent.getState(); + } + if (currVersion == null) { //probably it was not set + currVersion = currComponent.getVersion(); + } + } + AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory( + actionEnum, + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .serviceInstanceId(uuid) + .build(), + prevComponent, + ResourceAuditData.newBuilder() + .artifactUuid(currArtifactUid) + .state(currState) + .version(currVersion) + .distributionStatus(dcurrStatus) + .build(), + type.getValue().replace(" ", ""), compName, invariantUUID, + modifier, artifactData, comment, did, null); + + getAuditingManager().auditEvent(factory); + } + } + + public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + + getAuditingManager().auditEvent(auditingFields); + } + + + public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, + String environmentType, String action, String environmentName, String tenantContext) { + getAuditingManager().auditEvent(new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, + environmentType, action, tenantContext)); + } + + public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState, + String topicName, String distributionId, String description, String status, String workloadContext, String tenant) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, tenant); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, workloadContext); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, environmentName); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditAuthEvent(String url, String user, String authStatus, String realm) { + getAuditingManager().auditEvent(new AuditAuthRequestEventFactory( + CommonAuditData.newBuilder() + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + user, url, realm, authStatus)); + } + + public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId); + ThreadLocalsHolder.setUuid(distributionId); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) { + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName); + getAuditingManager().auditEvent(auditingFields); + } + + public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) { + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum, + CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + modifier, consumer); + + getAuditingManager().auditEvent(factory); + } + + public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + if (modifier != null) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + getAuditingManager().auditEvent(auditingFields); + } + + public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) { + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum, + CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + modifier, userBefore, userAfter); + + getAuditingManager().auditEvent(factory); + } + + public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) { + + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + user); + + getAuditingManager().auditEvent(factory); + } + + public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { + + EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + if (modifier != null) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + getAuditingManager().auditEvent(auditingFields); + } + + public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) { + if (component == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case COMPONENT_VERSION_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion()); + break; + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + case COMPONENT_IN_USE: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId()); + break; + case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public boolean validateStringNotEmpty(String value) { + return value != null && !value.trim().isEmpty(); + } + + public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) { + ActionStatus responseEnum; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; + break; + case INVALID_ID: + responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + switch (resultStatus) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ELEMENT_NOT_FOUND: + if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ + responseEnum = ActionStatus.PROPERTY_NOT_FOUND; + } + break; + case INVALID_PROPERTY_DEFAULT_VALUE: + case INVALID_PROPERTY_TYPE: + case INVALID_PROPERTY_VALUE: + case INVALID_PROPERTY_NAME: + case MISSING_ENTRY_SCHEMA_TYPE: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } + + public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { + + if (additionalInfoParameterInfo == null) { + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + } + if (labelOrValue == null) { + labelOrValue = AdditionalInformationEnum.None; + } + + ResponseFormat responseFormat = null; + switch (actionStatus) { + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey()); + break; + case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: + responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); + break; + case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: + responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase()); + break; + case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_NOT_FOUND: + responseFormat = getResponseFormat(actionStatus); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + + return responseFormat; + } + + public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) { + return getResponseFormatAdditionalProperty(actionStatus, null, null, null); + } + + public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; + break; + case NOT_FOUND: + responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; + break; + case CANNOT_UPDATE_EXISTING_ENTITY: + responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) { + if (groupType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case GROUP_MEMBER_EMPTY: + case GROUP_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, groupType.getType()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + + } + + public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) { + if (policyType == null) { + return getResponseFormat(actionStatus); + } + + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) { + responseFormat = getResponseFormat(actionStatus, policyType.getType()); + } + else { + responseFormat = getResponseFormat(actionStatus); + } + return responseFormat; + + } + + public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) { + if (dataType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case DATA_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: + responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); + break; + case DATA_TYPE_DERIVED_IS_MISSING: + responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName()); + break; + case DATA_TYPE_DUPLICATE_PROPERTY: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: + responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); + break; + case DATA_TYPE_CANNOT_HAVE_PROPERTIES: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java index ddc5ecabe7..b268554ee3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java @@ -20,143 +20,124 @@ package org.openecomp.sdc.be.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.eclipse.jgit.util.Base64; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.info.ArtifactAccessInfo; import org.openecomp.sdc.be.info.ArtifactAccessList; import org.openecomp.sdc.be.info.ServletJsonResponse; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; public class DownloadArtifactLogic { - private static Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class.getName()); - - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - public Response downloadArtifact(final String resourceName, final String resourceVersion, final String artifactName, Either<? extends ESArtifactData, ResourceUploadStatus> getArtifactStatus, String artifactId) { - Response response = null; - - if (getArtifactStatus.isRight()) { - log.debug("Could not find artifact for with id: {}", artifactId); - ResourceUploadStatus status = getArtifactStatus.right().value(); - if (status == status.COMPONENT_NOT_EXIST) - response = Response.status(HttpStatus.SC_NO_CONTENT).build(); - else - response = Response.status(HttpStatus.SC_NOT_FOUND).build(); - - return response; - } - // convert artifact to inputstream - else { - ESArtifactData artifactData = getArtifactStatus.left().value(); - byte[] artifactPayload = artifactData.getDataAsArray(); - - String payloadStr = new String(artifactPayload); - byte[] decodedPayload = artifactPayload; - log.debug("payload is encoded. perform decode"); - decodedPayload = Base64.decode(new String(artifactPayload)); - final InputStream artifactStream = new ByteArrayInputStream(decodedPayload); - log.debug("found artifact for with id: {}", artifactId); - try { - - // outputstream for response - StreamingOutput stream = new StreamingOutput() { - public void write(OutputStream output) throws IOException, WebApplicationException { - try { - IOUtils.copy(artifactStream, output); - } catch (Exception e) { - throw new WebApplicationException(e); - } - } - }; - artifactStream.close(); - return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment; filename = " + artifactName) - // .header(Constants.MD5_HEADER, new - // String(artifactData.getArtifactChecksum())) - .build(); - - } catch (IOException e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Failed to stream artifact data on the response"); - BeEcompErrorManager.getInstance().logBeSystemError("Failed to stream artifact data on the response"); - log.debug("Failed to stream artifact data on the response: {}", e.getMessage(), e); - response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to stream artifact data on the response"); - return response; - } - } - } - - public List<ArtifactAccessInfo> convertArtifactList(List<? extends ESArtifactData> artifactsList, String servletPath) { - - List<ArtifactAccessInfo> artifactAccessList = new ArrayList<ArtifactAccessInfo>(); - for (ESArtifactData artifact : artifactsList) { - ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath); - artifactAccessList.add(accessInfo); - } - return artifactAccessList; - } - - public Response createArtifactListResponse(final String serviceName, Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus/* - * List < ? extends IResourceData> artifactsList - */, String servletPath) { - Response response; - List<ArtifactAccessInfo> artifactAccessInfos; - if (getArtifactsStatus.isRight()) { - // if there are no artifacts - return No-Content - ResourceUploadStatus status = getArtifactsStatus.right().value(); - if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) { - log.debug("resource {} does not exist", serviceName); - response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build(); - - } else { - log.debug("No content was found for {}", serviceName); - response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build(); - } - return response; - } else { - List<? extends ESArtifactData> artifactsList = getArtifactsStatus.left().value(); - log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName); - artifactAccessInfos = convertArtifactList(artifactsList, servletPath); - - String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos)); - response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); - - return response; - } - } - - public Response buildResponse(int status, String errorMessage) { - - ServletJsonResponse jsonResponse = new ServletJsonResponse(); - jsonResponse.setDescription(errorMessage); - jsonResponse.setSource(Constants.CATALOG_BE); - - Response response = Response.status(status).entity(jsonResponse).build(); - - return response; - } + private static final Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class); + + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public Response downloadArtifact(final String artifactName, Either<? extends ESArtifactData, ResourceUploadStatus> getArtifactStatus, String artifactId) { + Response response = null; + + if (getArtifactStatus.isRight()) { + log.debug("Could not find artifact for with id: {}", artifactId); + ResourceUploadStatus status = getArtifactStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) + response = Response.status(HttpStatus.SC_NO_CONTENT).build(); + else + response = Response.status(HttpStatus.SC_NOT_FOUND).build(); + + return response; + } + // convert artifact to inputstream + else { + ESArtifactData artifactData = getArtifactStatus.left().value(); + byte[] artifactPayload = artifactData.getDataAsArray(); + + log.debug("payload is encoded. perform decode"); + byte[] decodedPayload = Base64.decode(new String(artifactPayload)); + final InputStream artifactStream = new ByteArrayInputStream(decodedPayload); + log.debug("found artifact for with id: {}", artifactId); + + // outputstream for response + StreamingOutput stream = output -> { + try { + IOUtils.copy(artifactStream, output); + } catch (IOException e) { + log.debug("failed to copy artifact payload into response"); + throw new WebApplicationException(e); + } + }; + return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .header("content-disposition", "attachment; filename = " + artifactName) + .build(); + + } + } + + public List<ArtifactAccessInfo> convertArtifactList(List<? extends ESArtifactData> artifactsList, String servletPath) { + + List<ArtifactAccessInfo> artifactAccessList = new ArrayList<ArtifactAccessInfo>(); + for (ESArtifactData artifact : artifactsList) { + ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath); + artifactAccessList.add(accessInfo); + } + return artifactAccessList; + } + + public Response createArtifactListResponse(final String serviceName, Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus/* + * List < ? extends IResourceData> artifactsList + */, String servletPath) { + Response response; + List<ArtifactAccessInfo> artifactAccessInfos; + if (getArtifactsStatus.isRight()) { + // if there are no artifacts - return No-Content + ResourceUploadStatus status = getArtifactsStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) { + log.debug("resource {} does not exist", serviceName); + response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build(); + + } else { + log.debug("No content was found for {}", serviceName); + response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build(); + } + return response; + } else { + List<? extends ESArtifactData> artifactsList = getArtifactsStatus.left().value(); + log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName); + artifactAccessInfos = convertArtifactList(artifactsList, servletPath); + + String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos)); + response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); + + return response; + } + } + + public Response buildResponse(int status, String errorMessage) { + + ServletJsonResponse jsonResponse = new ServletJsonResponse(); + jsonResponse.setDescription(errorMessage); + jsonResponse.setSource(Constants.CATALOG_BE); + + Response response = Response.status(status).entity(jsonResponse).build(); + + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java new file mode 100644 index 0000000000..2158508e56 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java @@ -0,0 +1,244 @@ +package org.openecomp.sdc.be.impl; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.SetMultimap; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.javatuples.Pair; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.datamodel.NameIdPair; +import org.openecomp.sdc.be.datamodel.NameIdPairWrapper; +import org.openecomp.sdc.be.datamodel.ServiceRelations; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; + +public class ForwardingPathUtils { + + public static final String FORWARDING_PATH_NODE_NAME = "Forwarding Path"; + public static final String FORWARDER_CAPABILITY = "org.openecomp.capabilities.Forwarder"; + + + public ServiceRelations convertServiceToServiceRelations(Service service) { + ServiceRelations serviceRelations = new ServiceRelations(); + List<ComponentInstance> componentInstances = service.getComponentInstances(); + if (componentInstances == null || componentInstances.isEmpty()) { + return serviceRelations; + } + Set<NameIdPairWrapper> relations = new HashSet<>(); + //@todo get all capabilities and requirements. + SetMultimap<NameIdPair, NameIdPair> nodeToCP = HashMultimap.create(); + componentInstances.forEach(ci -> initNodeToCP(ci, nodeToCP)); + handleRelDef(relations, nodeToCP); + serviceRelations.setRelations(relations); + return serviceRelations; + } + + private void initNodeToCP(ComponentInstance ci, SetMultimap<NameIdPair, NameIdPair> nodeToCP) { + Set<CapabilityDefinition> capabilities = ci.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()).collect(Collectors.toSet()); + if (!CollectionUtils.isNotEmpty(capabilities)) { + return; + } + Set<CapabilityDefinition> forwarderCapabilities = capabilities.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet()); + if (!CollectionUtils.isNotEmpty(forwarderCapabilities)) { + return; + } + NameIdPair node = new NameIdPair(ci.getName(), ci.getUniqueId()); + forwarderCapabilities.forEach(fc -> { + NameIdPair capability = new NameIdPair(fc.getName(), fc.getUniqueId(), fc.getOwnerId()); + nodeToCP.put(node, capability); + + }); + + } + + + private void handleRelDef(Set<NameIdPairWrapper> relations, SetMultimap<NameIdPair, NameIdPair> nodeToCP) { + nodeToCP.keySet().forEach(fromNode -> { + NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper(); + nameIdPairWrapper.init(fromNode); + if (!relations.contains(nameIdPairWrapper)) { + relations.add(nameIdPairWrapper); + Collection<NameIdPair> fromCps = nodeToCP.get(fromNode); + fromCps.forEach(fromCP -> handleFromCp(nodeToCP, nameIdPairWrapper)); + } + }); + + } + + private void handleFromCp(SetMultimap<NameIdPair, NameIdPair> nodeToCP, NameIdPairWrapper wrapper) { + Map<NameIdPair, Set<NameIdPair>> options = toMap(nodeToCP); + + Set<NameIdPair> cpOptions = options.get(wrapper.getNameIdPair()); + List<NameIdPairWrapper> wrappers = cpOptions.stream().map(cpOption -> createWrapper(cpOption)).collect(Collectors.toList()); + wrappers.forEach(cpOptionWrapper -> { + org.openecomp.sdc.be.datamodel.NameIdPair data = wrapper.getData(); + data.addWrappedData(cpOptionWrapper); + }); + addNodes(wrappers, options); + } + + private void addNodes(List<NameIdPairWrapper> cpOptions, Map<NameIdPair, Set<NameIdPair>> options) { + + cpOptions.forEach(cpOption -> { + Set<NameIdPairWrapper> wrappers = options.keySet().stream().map(option -> createWrapper(option)).collect(Collectors.toSet()); + wrappers.forEach(wrapper -> { + cpOption.getData().addWrappedData(wrapper); + Collection<NameIdPair> cps = options.get(wrapper.getNameIdPair()); + Set<NameIdPairWrapper> cpsWrappers = cps.stream().map(cp -> new NameIdPairWrapper(cp)).collect(Collectors.toSet()); + cpsWrappers.forEach(cpw -> { + NameIdPair data = wrapper.getData(); + if (!data.containsKey(cpw)) { + data.addWrappedData(cpw); + } + }); + }); + + }); + } + + private NameIdPairWrapper createWrapper(NameIdPair cpOption) { + NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper(); + nameIdPairWrapper.init(new NameIdPair(cpOption)); + return nameIdPairWrapper; + } + + + private Map<NameIdPair, Set<NameIdPair>> toMap(SetMultimap<NameIdPair, NameIdPair> nodeToCP) { + Map<NameIdPair, Set<NameIdPair>> retVal = new HashMap<>(); + nodeToCP.asMap().forEach((nameIdPair, nameIdPairs) -> retVal.put(nameIdPair, new HashSet<>(nameIdPairs))); + return retVal; + } + + + protected ResponseFormatManager getResponseFormatManager() { + return ResponseFormatManager.getInstance(); + } + + public Set<String> findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService, + String componentInstanceId) { + return findForwardingPathToDeleteOnCIDeletion(containerService, componentInstanceId).values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.toSet()); + } + + private Map<String, ForwardingPathDataDefinition> findForwardingPathToDeleteOnCIDeletion(Service containerService, + String componentInstanceId) { + return containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCI(entry, componentInstanceId)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + private boolean elementContainsCI(Map.Entry<String, ForwardingPathDataDefinition> fpEntry, + String componentInstanceId) { + return fpEntry.getValue().getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCI(element, componentInstanceId)); + } + + private boolean elementContainsCI(ForwardingPathElementDataDefinition elementDataDefinitions, + String componentInstanceId) { + return elementDataDefinitions.getFromNode().equals(componentInstanceId) + || elementDataDefinitions.getToNode().equals(componentInstanceId); + } + + public Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> updateForwardingPathOnVersionChange( + Service containerService, DataForMergeHolder dataHolder, + Component updatedContainerComponent, String newInstanceId) { + Map<String, ForwardingPathDataDefinition> updated = containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> updateCI(entry.getValue(), dataHolder.getOrigComponentInstId(),newInstanceId))); + Map<String, ForwardingPathDataDefinition> deleted = containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)); + return new Pair<>(updated, deleted); + } + + public Set<String> getForwardingPathsToBeDeletedOnVersionChange( + Service containerService, DataForMergeHolder dataHolder, Component updatedContainerComponent) { + return containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), + dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .map(entry -> entry.getValue().getUniqueId()).collect( Collectors.toSet()); + } + + private ForwardingPathDataDefinition updateCI(ForwardingPathDataDefinition inFP, String oldCI, String newCI) { + ForwardingPathDataDefinition retVal = new ForwardingPathDataDefinition(inFP); + List<ForwardingPathElementDataDefinition> fpList = retVal.getPathElements().getListToscaDataDefinition() + .stream().map(element -> updateElement(element, oldCI, newCI)).collect(Collectors.toList()); + retVal.setPathElements(new ListDataDefinition<>(fpList)); + return retVal; + } + + private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI, + String newCI) { + ForwardingPathElementDataDefinition retVal = new ForwardingPathElementDataDefinition(element); + if (retVal.getFromNode().equals(oldCI)) { + retVal.setFromNode(newCI); + } + if (retVal.getToNode().equals(oldCI)) { + retVal.setToNode(newCI); + } + if (Objects.equals(retVal.getToCPOriginId(),oldCI )) { + retVal.setToCPOriginId(newCI); + } + if (Objects.equals(retVal.getFromCPOriginId(),oldCI)) { + retVal.setFromCPOriginId(newCI); + } + return retVal; + } + + private boolean elementContainsCIAndForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition, + String oldCIId, Component newCI) { + return forwardingPathDataDefinition.getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCIAndForwarder(element, oldCIId, newCI)); + } + + private boolean elementContainsCIAndForwarder(ForwardingPathElementDataDefinition elementDataDefinitions, + String oldCIId, Component newCI) { + return (elementDataDefinitions.getFromNode().equals(oldCIId) && ciContainsForwarder(newCI, + elementDataDefinitions.getFromCP())) + || (elementDataDefinitions.getToNode().equals(oldCIId) && ciContainsForwarder(newCI, + elementDataDefinitions.getToCP())); + } + + private boolean ciContainsForwarder(Component newCI, String capabilityID) { + if (newCI.getCapabilities() == null){ + return false; + } + return newCI.getCapabilities().values() + .stream() + .flatMap(List::stream) + .anyMatch(c -> c.getUniqueId().equals(capabilityID)); + } + + private boolean elementContainsCIAndDoesNotContainForwarder( + ForwardingPathDataDefinition forwardingPathDataDefinition, + String oldCIId, Component newCI) { + return forwardingPathDataDefinition.getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCIAndDoesNotContainForwarder(element, oldCIId, newCI)); + } + + private boolean elementContainsCIAndDoesNotContainForwarder( + ForwardingPathElementDataDefinition elementDataDefinitions, + String oldCIId, Component newCI) { + return (elementDataDefinitions.getFromNode().equals(oldCIId) && !ciContainsForwarder(newCI, + elementDataDefinitions.getFromCP())) + || (elementDataDefinitions.getToNode().equals(oldCIId) && !ciContainsForwarder(newCI, + elementDataDefinitions.getToCP())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java index 3a5d9bf85f..c8128a33fc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.impl; -import javax.annotation.Resource; - +import com.google.gson.Gson; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.springframework.stereotype.Component; -import com.google.gson.Gson; +import javax.annotation.Resource; @Component("servletUtils") public class ServletUtils { - @Resource - private ComponentsUtils componentsUtils; - private Gson gson = new Gson(); - @Resource - private IUserBusinessLogic adminManager; - - public ComponentsUtils getComponentsUtils() { - return componentsUtils; - } - - public Gson getGson() { - return gson; - } - - public IUserBusinessLogic getUserAdmin() { - return adminManager; - } + @Resource + private ComponentsUtils componentsUtils; + private Gson gson = new Gson(); + @Resource + private IUserBusinessLogic adminManager; + + public ComponentsUtils getComponentsUtils() { + return componentsUtils; + } + + public Gson getGson() { + return gson; + } + + public IUserBusinessLogic getUserAdmin() { + return adminManager; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java index cb21984a7f..02759289b2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java @@ -20,16 +20,16 @@ package org.openecomp.sdc.be.impl; -import javax.servlet.ServletContext; - import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +import javax.servlet.ServletContext; + public class WebAppContextWrapper { - public WebApplicationContext getWebAppContext(ServletContext context) { + public WebApplicationContext getWebAppContext(ServletContext context) { - return WebApplicationContextUtils.getWebApplicationContext(context); - } + return WebApplicationContextUtils.getWebApplicationContext(context); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java index deb446e32f..d3fcf9f6c0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java @@ -17,143 +17,118 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import org.openecomp.sdc.be.resources.data.ESArtifactData; public class ArtifactAccessInfo { - public ArtifactAccessInfo() { - } - - public ArtifactAccessInfo(ESArtifactData artifactData) { - // this.name = artifactData.getArtifactName(); - this.id = artifactData.getId(); - // this.type = artifactData.getArtifactType(); - // this.description = artifactData.getArtifactDescription(); - // this.creator = artifactData.getArtifactCreator(); - // DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL); - // Date creationTimestamp = artifactData.getArtifactCreationTimestamp(); - // this.creationTime = (creationTimestamp != - // null)?dateFormat.format(creationTimestamp): null; - // Date updateTimestamp = artifactData.getArtifactLastUpdateTimestamp(); - // this.lastUpdateTime = (updateTimestamp != - // null)?dateFormat.format(updateTimestamp):null; - // this.lastUpdater = artifactData.getArtifactLastUpdater(); - // if (artifactData.getArtifactChecksum() != null){ - // this.checksum = new String(artifactData.getArtifactChecksum()); - // } else { - // this.checksum = null; - // } - } - - public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) { - // this.name = artifactData.getArtifactName(); - StringBuilder urlBuilder = new StringBuilder(); - urlBuilder = urlBuilder.append(servletContext).append("/"); - // if (ArtifactDataEnum.COMPONENT_ARTIFACT.equals(resource)){ - urlBuilder.append("resources/") - // .append(artifactData.getResourceId()).append("/") - - .append("/artifacts/"); - /* - * }else { ServiceArtifactData serviceArtifact = (ServiceArtifactData)artifactData; urlBuilder.append("services/") .append(serviceArtifact.getServiceName()).append("/") .append(serviceArtifact.getServiceVersion()) .append("/artifacts/") - * .append(serviceArtifact.getNodeTemplateName()) .append("/"); } - */ - // urlBuilder.append(artifactData.getArtifactName()); - this.url = urlBuilder.toString(); - - } - - private String name; - private String url; - private String id; - private String type; - private String description; - private String creator; - private String creationTime; - private String lastUpdater; - private String lastUpdateTime; - private String checksum; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - public String getCreationTime() { - return creationTime; - } - - public void setCreationTime(String creationTime) { - this.creationTime = creationTime; - } - - public String getLastUpdater() { - return lastUpdater; - } - - public void setLastUpdater(String lastUpdater) { - this.lastUpdater = lastUpdater; - } - - public String getLastUpdateTime() { - return lastUpdateTime; - } - - public void setLastUpdateTime(String lastUpdateTime) { - this.lastUpdateTime = lastUpdateTime; - } - - public String getChecksum() { - return checksum; - } - - public void setChecksum(String checksum) { - this.checksum = checksum; - } + public ArtifactAccessInfo() { + } + + public ArtifactAccessInfo(ESArtifactData artifactData) { + this.id = artifactData.getId(); + } + + public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) { + StringBuilder urlBuilder = new StringBuilder(); + urlBuilder = urlBuilder.append(servletContext).append("/"); + urlBuilder.append("resources/") + // .append(artifactData.getResourceId()).append("/") + + .append("/artifacts/"); + this.url = urlBuilder.toString(); + + } + + private String name; + private String url; + private String id; + private String type; + private String description; + private String creator; + private String creationTime; + private String lastUpdater; + private String lastUpdateTime; + private String checksum; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public String getCreationTime() { + return creationTime; + } + + public void setCreationTime(String creationTime) { + this.creationTime = creationTime; + } + + public String getLastUpdater() { + return lastUpdater; + } + + public void setLastUpdater(String lastUpdater) { + this.lastUpdater = lastUpdater; + } + + public String getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(String lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + public String getChecksum() { + return checksum; + } + + public void setChecksum(String checksum) { + this.checksum = checksum; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java index ddeb0505d9..635a082ad8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java @@ -24,17 +24,17 @@ import java.util.List; public class ArtifactAccessList { - public ArtifactAccessList(List<ArtifactAccessInfo> artifacts) { - this.artifacts = artifacts; - } + public ArtifactAccessList(List<ArtifactAccessInfo> artifacts) { + this.artifacts = artifacts; + } - private List<ArtifactAccessInfo> artifacts; + private List<ArtifactAccessInfo> artifacts; - public List<ArtifactAccessInfo> getArtifacts() { - return artifacts; - } + public List<ArtifactAccessInfo> getArtifacts() { + return artifacts; + } - public void setArtifacts(List<ArtifactAccessInfo> artifacts) { - this.artifacts = artifacts; - } + public void setArtifacts(List<ArtifactAccessInfo> artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java index dfdfeac741..bf257ee4f2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java @@ -24,60 +24,60 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; public class ArtifactDefinitionInfo { - private String uniqueId; - /** Specifies the display name of the artifact. */ - private String artifactName; - private String artifactDisplayName; - private String artifactVersion; - private String artifactUUID; - - public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) { - uniqueId = artifactDefinition.getUniqueId(); - artifactName = artifactDefinition.getArtifactName(); - artifactDisplayName = artifactDefinition.getArtifactDisplayName(); - artifactVersion = artifactDefinition.getArtifactVersion(); - artifactUUID = artifactDefinition.getArtifactUUID(); - - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactDisplayName() { - return artifactDisplayName; - } - - public void setArtifactDisplayName(String artifactDisplayName) { - this.artifactDisplayName = artifactDisplayName; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } + private String uniqueId; + /** Specifies the display name of the artifact. */ + private String artifactName; + private String artifactDisplayName; + private String artifactVersion; + private String artifactUUID; + + public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) { + uniqueId = artifactDefinition.getUniqueId(); + artifactName = artifactDefinition.getArtifactName(); + artifactDisplayName = artifactDefinition.getArtifactDisplayName(); + artifactVersion = artifactDefinition.getArtifactVersion(); + artifactUUID = artifactDefinition.getArtifactUUID(); + + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactDisplayName() { + return artifactDisplayName; + } + + public void setArtifactDisplayName(String artifactDisplayName) { + this.artifactDisplayName = artifactDisplayName; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java index f78b7dfead..9b8e81cc7b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java @@ -20,12 +20,9 @@ package org.openecomp.sdc.be.info; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -38,319 +35,316 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import fj.data.Either; +import java.util.*; public class ArtifactTemplateInfo { - public static final String TYPE = "type"; - public static final String FILE_NAME = "fileName"; - public static final String ENV = "env"; - public static final String IS_BASE = "isBase"; - - public static final String CSAR_HEAT = "HEAT"; - public static final String CSAR_ARTIFACT = "artifacts"; - public static final String CSAR_NETWORK = "network"; - public static final String CSAR_VOLUME = "volume"; - public static final String CSAR_NESTED = "nested"; - private static final Object DESC = "description"; - private static Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class.getName()); - String type; - String fileName; - String env; - boolean isBase; - String groupName; - String description; - - List<ArtifactTemplateInfo> relatedArtifactsInfo; - private static Gson gson = new Gson(); - - public ArtifactTemplateInfo() { - super(); - } - - public ArtifactTemplateInfo(String type, String fileName, String env, List<ArtifactTemplateInfo> relatedArtifactsInfo) { - super(); - this.type = type; - this.fileName = fileName; - this.env = env; - this.relatedArtifactsInfo = relatedArtifactsInfo; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - public List<ArtifactTemplateInfo> getRelatedArtifactsInfo() { - return relatedArtifactsInfo; - } - - public void setRelatedArtifactsInfo(List<ArtifactTemplateInfo> relatedArtifactsInfo) { - this.relatedArtifactsInfo = relatedArtifactsInfo; - } - - public String getGroupName() { - return groupName; - } - - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - public boolean isBase() { - return isBase; - } - - public void setBase(boolean isBase) { - this.isBase = isBase; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]"; - } - - public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map<String, Object> o, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, - ArtifactTemplateInfo parentArtifact) { - String content = gson.toJson(o); - JsonObject jsonElement = new JsonObject(); - ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo(); - - jsonElement = gson.fromJson(content, jsonElement.getClass()); - - Map<String, Object> artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class); - if (artifactTemplateMap.containsKey(TYPE)) - resourceInfo.setType((String) artifactTemplateMap.get(TYPE)); - if (artifactTemplateMap.containsKey(FILE_NAME)) - resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME)); - if (artifactTemplateMap.containsKey(IS_BASE)) - resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE)); - if (artifactTemplateMap.containsKey(ENV)) { - Object envObj = artifactTemplateMap.get(ENV); - String envStr = ""; - if (envObj instanceof String) { - envStr = (String) envObj; - } else if (envObj instanceof Map) { - Map envMap = (Map) envObj; - if (envMap.containsKey(FILE_NAME)) { - envStr = (String) envMap.get(FILE_NAME); - } - } - resourceInfo.setEnv(envStr); - } - if (artifactTemplateMap.containsKey(DESC)) { - resourceInfo.setDescription((String) artifactTemplateMap.get(DESC)); - } else { - resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME)); - } - - boolean artifactTypeExist = false; - String correctType = type; - if (type.equalsIgnoreCase(CSAR_NESTED)) - correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); - else if (type.equalsIgnoreCase(CSAR_VOLUME)) - correctType = ArtifactTypeEnum.HEAT_VOL.getType(); - else if (type.equalsIgnoreCase(CSAR_NETWORK)) - correctType = ArtifactTypeEnum.HEAT_NET.getType(); - else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ - if( parentArtifact != null) - correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); - else - correctType = resourceInfo.type; - } - else if (type.equalsIgnoreCase(CSAR_HEAT)) - correctType = ArtifactTypeEnum.HEAT.getType(); - else - correctType = ArtifactTypeEnum.OTHER.getType(); - Either<List<ArtifactType>, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource); - - if (allArtifactTypes.isRight()) { - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES)); - } - - for (ArtifactType artType : allArtifactTypes.left().value()) { - - if (artType.getName().contains(correctType)) { - resourceInfo.type = artType.getName(); - artifactTypeExist = true; - break; - } - } - - if (!artifactTypeExist) { - BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType); - log.debug("Not supported artifact type = {}" , correctType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType)); - } - - Either<Boolean, ResponseFormat> eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - Set<String> keys = o.keySet(); - for (String key : keys) { - if (o.get(key) instanceof List) { - List<Map<String, Object>> artifList = (List<Map<String, Object>>) o.get(key); - for (Map<String, Object> relatedArtifactsMap : artifList) { - Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo); - if (relatedArtifact.isRight()) - return relatedArtifact; - if (resourceInfo.relatedArtifactsInfo == null) - resourceInfo.relatedArtifactsInfo = new ArrayList<ArtifactTemplateInfo>(); - resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value()); - } - } - } - return Either.left(resourceInfo); - } - - private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) { - - if (parentArtifact == null) { - if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) - return Either.left(true); - for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) { - if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type)); - } - } - return Either.left(true); - } else { - List<ArtifactTemplateInfo> relatedArtifacts = parentArtifact.getRelatedArtifactsInfo(); - if (relatedArtifacts == null || relatedArtifacts.isEmpty()) - return Either.left(true); - for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) { - if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) { - if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName())); - } - } - } - return Either.left(true); - } - } - - private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) { - - if (parentArtifact == null) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) - && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { - return Either.left(true); - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.left(true); - } - return Either.left(true); - } - - private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) { - - if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) - return Either.left(true); - for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) { - // check if artifact with this name already parsed. If parsed check - // env name. it must be the same. - if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) { - if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) { - log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty() - && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) { - log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) { - log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - } - List<ArtifactTemplateInfo> relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo(); - Either<Boolean, ResponseFormat> status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo); - if (status.isRight()) - return status; - } - return Either.left(true); - } - - private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { - - Map<String, ArtifactTypeConfig> deploymentArtifacts = null; - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - - if (parentType.equals(NodeTypeEnum.Service)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } else { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } - if (deploymentArtifacts != null) { - for (String artifactType : deploymentArtifacts.keySet()) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return Either.left(artifactTypes); - } else { - return Either.right(ActionStatus.GENERAL_ERROR); - } - - } - - public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) { - return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0); - } + public static final String TYPE = "type"; + public static final String FILE_NAME = "fileName"; + public static final String ENV = "env"; + public static final String IS_BASE = "isBase"; + + public static final String CSAR_HEAT = "HEAT"; + public static final String CSAR_ARTIFACT = "artifacts"; + public static final String CSAR_NETWORK = "network"; + public static final String CSAR_VOLUME = "volume"; + public static final String CSAR_NESTED = "nested"; + private static final Object DESC = "description"; + private static final Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class); + String type; + String fileName; + String env; + boolean isBase; + String groupName; + String description; + + List<ArtifactTemplateInfo> relatedArtifactsInfo; + private static Gson gson = new Gson(); + + public ArtifactTemplateInfo() { + super(); + } + + public ArtifactTemplateInfo(String type, String fileName, String env, List<ArtifactTemplateInfo> relatedArtifactsInfo) { + super(); + this.type = type; + this.fileName = fileName; + this.env = env; + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getEnv() { + return env; + } + + public void setEnv(String env) { + this.env = env; + } + + public List<ArtifactTemplateInfo> getRelatedArtifactsInfo() { + return relatedArtifactsInfo; + } + + public void setRelatedArtifactsInfo(List<ArtifactTemplateInfo> relatedArtifactsInfo) { + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public boolean isBase() { + return isBase; + } + + public void setBase(boolean isBase) { + this.isBase = isBase; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]"; + } + + public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map<String, Object> o, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, + ArtifactTemplateInfo parentArtifact) { + String content = gson.toJson(o); + JsonObject jsonElement = new JsonObject(); + ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo(); + + jsonElement = gson.fromJson(content, jsonElement.getClass()); + + Map<String, Object> artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class); + if (artifactTemplateMap.containsKey(TYPE)) + resourceInfo.setType((String) artifactTemplateMap.get(TYPE)); + if (artifactTemplateMap.containsKey(FILE_NAME)) + resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME)); + if (artifactTemplateMap.containsKey(IS_BASE)) + resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE)); + if (artifactTemplateMap.containsKey(ENV)) { + Object envObj = artifactTemplateMap.get(ENV); + String envStr = ""; + if (envObj instanceof String) { + envStr = (String) envObj; + } else if (envObj instanceof Map) { + Map envMap = (Map) envObj; + if (envMap.containsKey(FILE_NAME)) { + envStr = (String) envMap.get(FILE_NAME); + } + } + resourceInfo.setEnv(envStr); + } + if (artifactTemplateMap.containsKey(DESC)) { + resourceInfo.setDescription((String) artifactTemplateMap.get(DESC)); + } else { + resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME)); + } + + boolean artifactTypeExist = false; + String correctType = type; + if (type.equalsIgnoreCase(CSAR_NESTED)) + correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); + else if (type.equalsIgnoreCase(CSAR_VOLUME)) + correctType = ArtifactTypeEnum.HEAT_VOL.getType(); + else if (type.equalsIgnoreCase(CSAR_NETWORK)) + correctType = ArtifactTypeEnum.HEAT_NET.getType(); + else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ + if( parentArtifact != null) + correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); + else + correctType = resourceInfo.type; + } + else if (type.equalsIgnoreCase(CSAR_HEAT)) + correctType = ArtifactTypeEnum.HEAT.getType(); + else + correctType = ArtifactTypeEnum.OTHER.getType(); + Either<List<ArtifactType>, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource); + + if (allArtifactTypes.isRight()) { + BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES)); + } + + for (ArtifactType artType : allArtifactTypes.left().value()) { + + if (artType.getName().contains(correctType)) { + resourceInfo.type = artType.getName(); + artifactTypeExist = true; + break; + } + } + + if (!artifactTypeExist) { + BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType); + log.debug("Not supported artifact type = {}" , correctType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType)); + } + + Either<Boolean, ResponseFormat> eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + Set<String> keys = o.keySet(); + for (String key : keys) { + if (o.get(key) instanceof List) { + List<Map<String, Object>> artifList = (List<Map<String, Object>>) o.get(key); + for (Map<String, Object> relatedArtifactsMap : artifList) { + Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo); + if (relatedArtifact.isRight()) + return relatedArtifact; + if (resourceInfo.relatedArtifactsInfo == null) + resourceInfo.relatedArtifactsInfo = new ArrayList<ArtifactTemplateInfo>(); + resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value()); + } + } + } + return Either.left(resourceInfo); + } + + private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) { + + if (parentArtifact == null) { + if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) + return Either.left(true); + for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) { + if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type)); + } + } + return Either.left(true); + } else { + List<ArtifactTemplateInfo> relatedArtifacts = parentArtifact.getRelatedArtifactsInfo(); + if (relatedArtifacts == null || relatedArtifacts.isEmpty()) + return Either.left(true); + for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) { + if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) { + if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName())); + } + } + } + return Either.left(true); + } + } + + private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) { + + if (parentArtifact == null) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) + && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { + return Either.left(true); + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.left(true); + } + return Either.left(true); + } + + private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) { + + if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) + return Either.left(true); + for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) { + // check if artifact with this name already parsed. If parsed check + // env name. it must be the same. + if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) { + if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) { + log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty() + && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) { + log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) { + log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + } + List<ArtifactTemplateInfo> relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo(); + Either<Boolean, ResponseFormat> status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo); + if (status.isRight()) + return status; + } + return Either.left(true); + } + + private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { + + Map<String, ArtifactTypeConfig> deploymentArtifacts = null; + List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); + + if (parentType.equals(NodeTypeEnum.Service)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); + } else { + deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + } + if (deploymentArtifacts != null) { + for (String artifactType : deploymentArtifacts.keySet()) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return Either.left(artifactTypes); + } else { + return Either.right(ActionStatus.GENERAL_ERROR); + } + + } + + public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) { + return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java index 249b420908..5d635f05ff 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java @@ -20,29 +20,29 @@ package org.openecomp.sdc.be.info; -import java.util.List; - import org.openecomp.sdc.be.model.ArtifactType; +import java.util.List; + public class ArtifactTypesInfo { - Integer heatDefaultTimeout = 60; - List<ArtifactType> artifactTypes; + Integer heatDefaultTimeout = 60; + List<ArtifactType> artifactTypes; - public List<ArtifactType> getArtifactTypes() { - return artifactTypes; - } + public List<ArtifactType> getArtifactTypes() { + return artifactTypes; + } - public void setArtifactTypes(List<ArtifactType> artifactTypes) { - this.artifactTypes = artifactTypes; - } + public void setArtifactTypes(List<ArtifactType> artifactTypes) { + this.artifactTypes = artifactTypes; + } - public Integer getHeatDefaultTimeout() { - return heatDefaultTimeout; - } + public Integer getHeatDefaultTimeout() { + return heatDefaultTimeout; + } - public void setHeatDefaultTimeout(Integer heatDefaultTimeout) { - this.heatDefaultTimeout = heatDefaultTimeout; - } + public void setHeatDefaultTimeout(Integer heatDefaultTimeout) { + this.heatDefaultTimeout = heatDefaultTimeout; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java index b2fa493443..a7847a164d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java @@ -24,29 +24,29 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; public class CreateAndAssotiateInfo { - private ComponentInstance node; - private RequirementCapabilityRelDef associate; - - public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) { - super(); - this.node = node; - this.associate = associate; - } - - public ComponentInstance getNode() { - return node; - } - - public void setNode(ComponentInstance node) { - this.node = node; - } - - public RequirementCapabilityRelDef getAssociate() { - return associate; - } - - public void setAssociate(RequirementCapabilityRelDef associate) { - this.associate = associate; - } + private ComponentInstance node; + private RequirementCapabilityRelDef associate; + + public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) { + super(); + this.node = node; + this.associate = associate; + } + + public ComponentInstance getNode() { + return node; + } + + public void setNode(ComponentInstance node) { + this.node = node; + } + + public RequirementCapabilityRelDef getAssociate() { + return associate; + } + + public void setAssociate(RequirementCapabilityRelDef associate) { + this.associate = associate; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java index d0f3ff868e..795d5f6046 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java @@ -24,39 +24,39 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public enum DistributionStatus { - DEPLOYED("Deployed", "DEPLOYED"); - - private String name; - private String auditingStatus; - - private static Logger log = LoggerFactory.getLogger(DistributionStatus.class.getName()); - - DistributionStatus(String name, String auditingStatus) { - this.name = name; - this.auditingStatus = auditingStatus; - } - - public String getName() { - return name; - } - - public String getAuditingStatus() { - return auditingStatus; - } - - public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) { - DistributionStatus res = null; - DistributionStatus[] values = values(); - for (DistributionStatus value : values) { - if (value.getAuditingStatus().equals(auditingStatus)) { - res = value; - break; - } - } - if (res == null) { - log.debug("No DistributionStatus is mapped to name {}", auditingStatus); - } - return res; - } + DEPLOYED("Deployed", "DEPLOYED"); + + private String name; + private String auditingStatus; + + private static final Logger log = LoggerFactory.getLogger(DistributionStatus.class); + + DistributionStatus(String name, String auditingStatus) { + this.name = name; + this.auditingStatus = auditingStatus; + } + + public String getName() { + return name; + } + + public String getAuditingStatus() { + return auditingStatus; + } + + public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) { + DistributionStatus res = null; + DistributionStatus[] values = values(); + for (DistributionStatus value : values) { + if (value.getAuditingStatus().equals(auditingStatus)) { + res = value; + break; + } + } + if (res == null) { + log.debug("No DistributionStatus is mapped to name {}", auditingStatus); + } + return res; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java index 6f7596cd5f..dd8ef32124 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java @@ -24,68 +24,68 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; public class DistributionStatusInfo { - String omfComponentID; - String timestamp; - String url; - String status; - String errorReason; - - public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) { - super(); - omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName()); - timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime(); - url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL(); - status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus(); - errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName()); - - } - - public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) { - super(); - this.omfComponentID = omfComponentID; - this.timestamp = timestamp; - this.url = url; - this.status = status; - } - - public String getOmfComponentID() { - return omfComponentID; - } - - public void setOmfComponentID(String omfComponentID) { - this.omfComponentID = omfComponentID; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } + String omfComponentID; + String timestamp; + String url; + String status; + String errorReason; + + public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) { + super(); + omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName()); + timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime(); + url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL(); + status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus(); + errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName()); + + } + + public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) { + super(); + this.omfComponentID = omfComponentID; + this.timestamp = timestamp; + this.url = url; + this.status = status; + } + + public String getOmfComponentID() { + return omfComponentID; + } + + public void setOmfComponentID(String omfComponentID) { + this.omfComponentID = omfComponentID; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java index ab122efc74..1f3fb90f78 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java @@ -24,14 +24,14 @@ import java.util.List; public class DistributionStatusListResponse { - private List<DistributionStatusInfo> distribStatusInfoList; + private List<DistributionStatusInfo> distribStatusInfoList; - public List<DistributionStatusInfo> getDistributionStatusList() { - return distribStatusInfoList; - } + public List<DistributionStatusInfo> getDistributionStatusList() { + return distribStatusInfoList; + } - public void setDistributionStatusList(List<DistributionStatusInfo> distribStatusInfoList) { - this.distribStatusInfoList = distribStatusInfoList; - } + public void setDistributionStatusList(List<DistributionStatusInfo> distribStatusInfoList) { + this.distribStatusInfoList = distribStatusInfoList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java index dfa481d34d..533ca7e99f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java @@ -21,54 +21,54 @@ package org.openecomp.sdc.be.info; public class DistributionStatusOfServiceInfo { - String distributionID; - String timestamp; - String userId; - String deployementStatus; + String distributionID; + String timestamp; + String userId; + String deployementStatus; - public DistributionStatusOfServiceInfo() { - super(); + public DistributionStatusOfServiceInfo() { + super(); - } + } - public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) { - super(); - this.distributionID = distributionID; - this.timestamp = timestamp; - this.userId = userId; - this.deployementStatus = deployementStatus; - } + public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) { + super(); + this.distributionID = distributionID; + this.timestamp = timestamp; + this.userId = userId; + this.deployementStatus = deployementStatus; + } - public String getDistributionID() { - return distributionID; - } + public String getDistributionID() { + return distributionID; + } - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } - public String getTimestamp() { - return timestamp; - } + public String getTimestamp() { + return timestamp; + } - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getDeployementStatus() { - return deployementStatus; - } + public String getDeployementStatus() { + return deployementStatus; + } - public void setDeployementStatus(String deployementStatus) { - this.deployementStatus = deployementStatus; - } + public void setDeployementStatus(String deployementStatus) { + this.deployementStatus = deployementStatus; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java index 8415736be1..023645fa2d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java @@ -24,14 +24,14 @@ import java.util.List; public class DistributionStatusOfServiceListResponce { - private List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList; + private List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList; - public List<DistributionStatusOfServiceInfo> getDistributionStatusOfServiceList() { - return distribStatusOfServiceInfoList; - } + public List<DistributionStatusOfServiceInfo> getDistributionStatusOfServiceList() { + return distribStatusOfServiceInfoList; + } - public void setDistributionStatusOfServiceList(List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList) { - this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList; - } + public void setDistributionStatusOfServiceList(List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList) { + this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java index ea495267bd..f49315c0d0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java @@ -20,157 +20,157 @@ package org.openecomp.sdc.be.info; -import java.util.List; - import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupProperty; +import java.util.List; + public class GroupDefinitionInfo { - private String name; - - // the id is unique per group instance on graph. - private String uniqueId; - - // the id is unique per group instance on graph. - private String groupInstanceUniqueId; - - // the group UUID should be changed when one of the artifacts/component - // instances has been changed. - private String groupUUID; - - // version should be changed when there is a change to the group's metadata - // or to the groups members - // (not necessarily when the VF version is changed). This field cannot be - // updated by user - private String version; - - private String invariantUUID; - private String customizationUUID; - - Boolean isBase = null; - - // artifacts - list of artifact uid. All artifacts in the group must already - // be uploaded to the VF - private List<ArtifactDefinitionInfo> artifacts; - - private List<? extends GroupProperty> properties; - - public GroupDefinitionInfo() { - super(); - } - - public GroupDefinitionInfo(GroupDefinition other) { - this.setName(other.getName()); - this.setUniqueId(other.getUniqueId()); - this.setVersion(other.getVersion()); - this.setGroupUUID(other.getGroupUUID()); - this.setInvariantUUID(other.getInvariantUUID()); - this.setProperties(other.convertToGroupProperties()); - - - } - - public GroupDefinitionInfo(GroupInstance other) { - this.setName(other.getGroupName()); - this.setUniqueId(other.getGroupUid()); - this.setGroupInstanceUniqueId(other.getUniqueId()); - this.setVersion(other.getVersion()); - this.setGroupUUID(other.getGroupUUID()); - this.setCustomizationUUID(other.getCustomizationUUID()); - this.setInvariantUUID(other.getInvariantUUID()); - this.setProperties(other.convertToGroupInstancesProperties()); - - - } - - public String getInvariantUUID() { - return invariantUUID; - } - - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getGroupUUID() { - return groupUUID; - } - - public void setGroupUUID(String groupUUID) { - this.groupUUID = groupUUID; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - - public String getCustomizationUUID() { - return customizationUUID; - } - - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public Boolean getIsBase() { - return isBase; - } - - public void setIsBase(Boolean isBase) { - this.isBase = isBase; - } - - public List<ArtifactDefinitionInfo> getArtifacts() { - return artifacts; - } - - public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) { - this.artifacts = artifacts; - } - - public List<? extends GroupProperty> getProperties() { - return properties; - } - - public void setProperties(List<? extends GroupProperty> properties) { - this.properties = properties; - } - - - - public String getGroupInstanceUniqueId() { - return groupInstanceUniqueId; - } - - public void setGroupInstanceUniqueId(String groupInstanceUniqueId) { - this.groupInstanceUniqueId = groupInstanceUniqueId; - } - - @Override - public String toString() { - return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]"; - } - + private String name; + + // the id is unique per group instance on graph. + private String uniqueId; + + // the id is unique per group instance on graph. + private String groupInstanceUniqueId; + + // the group UUID should be changed when one of the artifacts/component + // instances has been changed. + private String groupUUID; + + // version should be changed when there is a change to the group's metadata + // or to the groups members + // (not necessarily when the VF version is changed). This field cannot be + // updated by user + private String version; + + private String invariantUUID; + private String customizationUUID; + + Boolean isBase = null; + + // artifacts - list of artifact uid. All artifacts in the group must already + // be uploaded to the VF + private List<ArtifactDefinitionInfo> artifacts; + + private List<? extends GroupProperty> properties; + + public GroupDefinitionInfo() { + super(); + } + + public GroupDefinitionInfo(GroupDefinition other) { + this.setName(other.getName()); + this.setUniqueId(other.getUniqueId()); + this.setVersion(other.getVersion()); + this.setGroupUUID(other.getGroupUUID()); + this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupProperties()); + + + } + + public GroupDefinitionInfo(GroupInstance other) { + this.setName(other.getGroupName()); + this.setUniqueId(other.getGroupUid()); + this.setGroupInstanceUniqueId(other.getUniqueId()); + this.setVersion(other.getVersion()); + this.setGroupUUID(other.getGroupUUID()); + this.setCustomizationUUID(other.getCustomizationUUID()); + this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupInstancesProperties()); + + + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getGroupUUID() { + return groupUUID; + } + + public void setGroupUUID(String groupUUID) { + this.groupUUID = groupUUID; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public Boolean getIsBase() { + return isBase; + } + + public void setIsBase(Boolean isBase) { + this.isBase = isBase; + } + + public List<ArtifactDefinitionInfo> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) { + this.artifacts = artifacts; + } + + public List<? extends GroupProperty> getProperties() { + return properties; + } + + public void setProperties(List<? extends GroupProperty> properties) { + this.properties = properties; + } + + + + public String getGroupInstanceUniqueId() { + return groupInstanceUniqueId; + } + + public void setGroupInstanceUniqueId(String groupInstanceUniqueId) { + this.groupInstanceUniqueId = groupInstanceUniqueId; + } + + @Override + public String toString() { + return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java index 4a7e925639..301cffafdc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java @@ -21,36 +21,36 @@ package org.openecomp.sdc.be.info; public class GroupTemplateInfo { - String groupName; - boolean isBase; - ArtifactTemplateInfo artifactTemplateInfo; + String groupName; + boolean isBase; + ArtifactTemplateInfo artifactTemplateInfo; - public GroupTemplateInfo() { - super(); - } + public GroupTemplateInfo() { + super(); + } - public String getGroupName() { - return groupName; - } + public String getGroupName() { + return groupName; + } - public void setGroupName(String groupName) { - this.groupName = groupName; - } + public void setGroupName(String groupName) { + this.groupName = groupName; + } - public boolean isBase() { - return isBase; - } + public boolean isBase() { + return isBase; + } - public void setBase(boolean isBase) { - this.isBase = isBase; - } + public void setBase(boolean isBase) { + this.isBase = isBase; + } - public ArtifactTemplateInfo getArtifactTemplateInfo() { - return artifactTemplateInfo; - } + public ArtifactTemplateInfo getArtifactTemplateInfo() { + return artifactTemplateInfo; + } - public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) { - this.artifactTemplateInfo = artifactTemplateInfo; - } + public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) { + this.artifactTemplateInfo = artifactTemplateInfo; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java index 62ee5b6f81..e4b6f35cba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java @@ -20,150 +20,145 @@ package org.openecomp.sdc.be.info; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.model.ArtifactDefinition; +import java.util.*; public class MergedArtifactInfo { - private List<ArtifactDefinition> createdArtifact; - private ArtifactTemplateInfo jsonArtifactTemplate; - private Set<String> parsetArtifactsNames; - - public List<ArtifactDefinition> getCreatedArtifact() { - return createdArtifact; - } - - public void setCreatedArtifact(List<ArtifactDefinition> createdArtifact) { - this.createdArtifact = createdArtifact; - parsetArtifactsNames = new HashSet<String>(); - parsetArtifactsNames.add(jsonArtifactTemplate.getFileName()); - List<ArtifactTemplateInfo> relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { - this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames); - } - - } - - public ArtifactTemplateInfo getJsonArtifactTemplate() { - return jsonArtifactTemplate; - } - - public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) { - this.jsonArtifactTemplate = jsonArtifactTemplate; - } - - public List<ArtifactTemplateInfo> getListToAssociateArtifactToGroup() { - List<ArtifactTemplateInfo> resList = new ArrayList<ArtifactTemplateInfo>(); - List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getNewArtifactsInGroup(resList, relatedArtifacts); - } - return resList; - } - - public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) { - List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>(); - for (ArtifactDefinition artifactDefinition : createdArtifact) { - boolean isDissotiate = true; - if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){ - isDissotiate = false; - }else{ - if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){ - Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); - if(op.isPresent()){ - ArtifactDefinition generatedFromArt = op.get(); - if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){ - isDissotiate = false; - } - } - else{ - isDissotiate = true; - } - - } - } - if (isDissotiate) { - boolean isDeleted = false; - for (ArtifactDefinition deletedArtifact : deletedArtifacts) { - if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) { - isDeleted = true; - break; - } - - } - if (!isDeleted) - resList.add(artifactDefinition); - } - - } - - return resList; - } - - public List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> getListToUpdateArtifactInGroup() { - List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList = new ArrayList<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>(); - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) { - resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, jsonArtifactTemplate)); - } - } - List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getUpdateArtifactsInGroup(resList, relatedArtifacts); - } - return resList; - } - - private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList, List<ArtifactTemplateInfo> jsonArtifacts) { - - for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { - - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { - resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, artifactTemplateInfo)); - } - } - - List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getUpdateArtifactsInGroup(resList, relatedArtifacts); - } - } - } - - private void getNewArtifactsInGroup(List<ArtifactTemplateInfo> resList, List<ArtifactTemplateInfo> jsonArtifacts) { - - for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { - boolean isNewArtifact = true; - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { - isNewArtifact = false; - } - } - if (isNewArtifact) - resList.add(artifactTemplateInfo); - List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getNewArtifactsInGroup(resList, relatedArtifacts); - } - } - } - - private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<String> parsedArtifactsName) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - parsedArtifactsName.add(parsedGroupTemplate.getFileName()); - List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); - } - } - } + private List<ArtifactDefinition> createdArtifact; + private ArtifactTemplateInfo jsonArtifactTemplate; + private Set<String> parsetArtifactsNames; + + public List<ArtifactDefinition> getCreatedArtifact() { + return createdArtifact; + } + + public void setCreatedArtifact(List<ArtifactDefinition> createdArtifact) { + this.createdArtifact = createdArtifact; + parsetArtifactsNames = new HashSet<String>(); + parsetArtifactsNames.add(jsonArtifactTemplate.getFileName()); + List<ArtifactTemplateInfo> relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { + this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames); + } + + } + + public ArtifactTemplateInfo getJsonArtifactTemplate() { + return jsonArtifactTemplate; + } + + public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) { + this.jsonArtifactTemplate = jsonArtifactTemplate; + } + + public List<ArtifactTemplateInfo> getListToAssociateArtifactToGroup() { + List<ArtifactTemplateInfo> resList = new ArrayList<ArtifactTemplateInfo>(); + List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getNewArtifactsInGroup(resList, relatedArtifacts); + } + return resList; + } + + public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) { + List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>(); + for (ArtifactDefinition artifactDefinition : createdArtifact) { + boolean isDissotiate = true; + if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){ + isDissotiate = false; + }else{ + if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){ + Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); + if(op.isPresent()){ + ArtifactDefinition generatedFromArt = op.get(); + if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){ + isDissotiate = false; + } + } + else{ + isDissotiate = true; + } + + } + } + if (isDissotiate) { + boolean isDeleted = false; + for (ArtifactDefinition deletedArtifact : deletedArtifacts) { + if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) { + isDeleted = true; + break; + } + + } + if (!isDeleted) + resList.add(artifactDefinition); + } + + } + + return resList; + } + + public List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> getListToUpdateArtifactInGroup() { + List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList = new ArrayList<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>(); + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) { + resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, jsonArtifactTemplate)); + } + } + List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getUpdateArtifactsInGroup(resList, relatedArtifacts); + } + return resList; + } + + private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList, List<ArtifactTemplateInfo> jsonArtifacts) { + + for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { + + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { + resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, artifactTemplateInfo)); + } + } + + List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getUpdateArtifactsInGroup(resList, relatedArtifacts); + } + } + } + + private void getNewArtifactsInGroup(List<ArtifactTemplateInfo> resList, List<ArtifactTemplateInfo> jsonArtifacts) { + + for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { + boolean isNewArtifact = true; + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { + isNewArtifact = false; + } + } + if (isNewArtifact) + resList.add(artifactTemplateInfo); + List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getNewArtifactsInGroup(resList, relatedArtifacts); + } + } + } + + private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<String> parsedArtifactsName) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + parsedArtifactsName.add(parsedGroupTemplate.getFileName()); + List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java new file mode 100644 index 0000000000..766581bd62 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java @@ -0,0 +1,41 @@ +package org.openecomp.sdc.be.info; + +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class NodeTypeInfoToUpdateArtifacts { + + private String nodeName; + private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle; + + + public NodeTypeInfoToUpdateArtifacts(String nodeName, + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle) { + super(); + this.nodeName = nodeName; + this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle; + } + + public String getNodeName() { + return nodeName; + } + + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } + + public Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> getNodeTypesArtifactsToHandle() { + return nodeTypesArtifactsToHandle; + } + + public void setNodeTypesArtifactsToHandle( + Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle) { + this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java new file mode 100644 index 0000000000..4d27713e22 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java @@ -0,0 +1,123 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public final class OperationalEnvInfo { + @JsonIgnore + private static ObjectMapper objectMapper = new ObjectMapper(); + + @JsonIgnore + private static final Logger logger = LoggerFactory.getLogger(OperationalEnvInfo.class); + + @JsonProperty("operational-environment-id") + private String operationalEnvId; + + @JsonProperty("operational-environment-name") + private String operationalEnvName; + + @JsonProperty("operational-environment-type") + private String operationalEnvType; + + @JsonProperty("operational-environment-status") + private String operationalEnvStatus; + + @JsonProperty("tenant-context") + private String tenantContext; + + @JsonProperty("workload-context") + private String workloadContext; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("relationship-list") + private RelationshipList relationships; + + public String getOperationalEnvId() { + return operationalEnvId; + } + + public void setOperationalEnvId(String operationalEnvId) { + this.operationalEnvId = operationalEnvId; + } + + public String getOperationalEnvName() { + return operationalEnvName; + } + + public void setOperationalEnvName(String operationalEnvName) { + this.operationalEnvName = operationalEnvName; + } + + public String getOperationalEnvType() { + return operationalEnvType; + } + + public void setOperationalEnvType(String operationalEnvType) { + this.operationalEnvType = operationalEnvType; + } + + public String getOperationalEnvStatus() { + return operationalEnvStatus; + } + + public void setOperationalEnvStatus(String operationalEnvStatus) { + this.operationalEnvStatus = operationalEnvStatus; + } + + public String getTenantContext() { + return tenantContext; + } + + public void setTenantContext(String tenantContext) { + this.tenantContext = tenantContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public RelationshipList getRelationships() { + return relationships; + } + + public void setRelationships(RelationshipList relationships) { + this.relationships = relationships; + } + + @Override + public String toString() { + try { + return objectMapper.writeValueAsString(this); + } + catch (JsonProcessingException e) { + logger.debug("Convert object to string failed with exception. ", e); + return StringUtils.EMPTY; + } + } + + public static OperationalEnvInfo createFromJson(String json) throws IOException { + return objectMapper.readValue(json, OperationalEnvInfo.class); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java new file mode 100644 index 0000000000..5684c9b57f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public final class RelatedToProperty { + + @JsonProperty("property-key") + private String propertyKey; + + @JsonProperty("property-value") + private String propertyValue; + + public String getPropertyKey() { + return propertyKey; + } + + public void setPropertyKey(String propertyKey) { + this.propertyKey = propertyKey; + } + + public String getPropertyValue() { + return propertyValue; + } + + public void setPropertyValue(String propertyValue) { + this.propertyValue = propertyValue; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java new file mode 100644 index 0000000000..fba6632698 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +public final class Relationship { + + @JsonProperty("related-to") + private String relatedTo; + + @JsonProperty(value="relationship-label") + private String relationshipLabel; + + @JsonProperty(value="related-link", required=false) + private String relatedLink; + + @JsonProperty("relationship-data") + private List<RelationshipData> relationshipData; + + @JsonProperty("related-to-property") + private List<RelatedToProperty> relatedToProperty; + + public String getRelatedTo() { + return relatedTo; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } + + public List<RelationshipData> getRelationshipData() { + if(relationshipData == null) { + relationshipData = new ArrayList<>(); + } + return relationshipData; + } + + public void setRelationshipData(List<RelationshipData> relationshipData) { + this.relationshipData = relationshipData; + } + + public String getRelationshipLabel() { + return relationshipLabel; + } + + public void setRelationshipLabel(String relationshipLabel) { + this.relationshipLabel = relationshipLabel; + } + + public List<RelatedToProperty> getRelatedToProperty() { + if(relatedToProperty == null) { + relatedToProperty = new ArrayList<>(); + } + return relatedToProperty; + } + + public void setRelatedToProperty(List<RelatedToProperty> relatedToProperty) { + this.relatedToProperty = relatedToProperty; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java new file mode 100644 index 0000000000..2b01daecd4 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public final class RelationshipData { + + @JsonProperty("relationship-key") + private String relationshipKey; + + @JsonProperty("relationship-value") + private String relationshipValue; + + public void setRelationshipkey(String relationshipKey) { + this.relationshipKey = relationshipKey; + } + + public String getRelationshipKey() { + return this.relationshipKey; + } + + public void setRelationshipValue(String relationshipValue) { + this.relationshipValue = relationshipValue; + } + + public String getRelationshipValue() { + return this.relationshipValue; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java new file mode 100644 index 0000000000..6a09a84d6e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.info; + +import java.util.ArrayList; +import java.util.List; + +public class RelationshipList { + private List<Relationship> relationship; + + public List<Relationship> getRelationship() { + if(relationship == null) { + relationship = new ArrayList<>(); + } + return relationship; + } + + public void setRelationship(List<Relationship> relationship) { + this.relationship = relationship; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java index 457c49ee8e..99395350cb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java @@ -24,28 +24,28 @@ import java.util.List; public class ServiceInfo { - private String name; - private List<ServiceVersionInfo> versions; + private String name; + private List<ServiceVersionInfo> versions; - public ServiceInfo(String serviceName, List<ServiceVersionInfo> list) { - this.name = serviceName; - this.versions = list; - } + public ServiceInfo(String serviceName, List<ServiceVersionInfo> list) { + this.name = serviceName; + this.versions = list; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List<ServiceVersionInfo> getVersions() { - return versions; - } + public List<ServiceVersionInfo> getVersions() { + return versions; + } - public void setVersions(List<ServiceVersionInfo> versions) { - this.versions = versions; - } + public void setVersions(List<ServiceVersionInfo> versions) { + this.versions = versions; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java index 13f8a1307f..32c7c54528 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java @@ -22,32 +22,30 @@ package org.openecomp.sdc.be.info; public class ServiceVersionInfo { - // private String serviceName; - private String version; - private String url; - - public ServiceVersionInfo(String serviceName, String serviceVersion, String context) { - super(); - // this.serviceName = serviceName; - this.version = serviceVersion; - StringBuilder sb = new StringBuilder(context); - sb.append("services/").append(serviceName).append("/").append(serviceVersion); - url = sb.toString(); - } - - public String getVersion() { - return version; - } - - public void setVersion(String serviceVersion) { - this.version = serviceVersion; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } + private String version; + private String url; + + public ServiceVersionInfo(String serviceName, String serviceVersion, String context) { + super(); + this.version = serviceVersion; + StringBuilder sb = new StringBuilder(context); + sb.append("services/").append(serviceName).append("/").append(serviceVersion); + url = sb.toString(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String serviceVersion) { + this.version = serviceVersion; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java index 9c26cf5959..00f41ad434 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java @@ -23,13 +23,13 @@ package org.openecomp.sdc.be.info; import java.util.List; public class ServicesWrapper { - private List<ServiceInfo> services; + private List<ServiceInfo> services; - public List<ServiceInfo> getServices() { - return services; - } + public List<ServiceInfo> getServices() { + return services; + } - public void setServices(List<ServiceInfo> services) { - this.services = services; - } + public void setServices(List<ServiceInfo> services) { + this.services = services; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java index 5559311e9e..ae2032eb43 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java @@ -22,23 +22,23 @@ package org.openecomp.sdc.be.info; public class ServletJsonResponse { - String source; - String description; + String source; + String description; - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getSource() { - return source; - } + public String getSource() { + return source; + } - public void setSource(String source) { - this.source = source; - } + public void setSource(String source) { + this.source = source; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java index 11b27af7a1..031477cfe9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java @@ -24,46 +24,46 @@ import java.util.List; public class ToscaNodeTypeInfo { - private String nodeName; - private String templateVersion; - private List<ToscaNodeTypeInterface> interfaces; - private String iconPath; + private String nodeName; + private String templateVersion; + private List<ToscaNodeTypeInterface> interfaces; + private String iconPath; - public String getNodeName() { - return nodeName; - } + public String getNodeName() { + return nodeName; + } - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } - public String getTemplateVersion() { - return templateVersion; - } + public String getTemplateVersion() { + return templateVersion; + } - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } - public List<ToscaNodeTypeInterface> getInterfaces() { - return interfaces; - } + public List<ToscaNodeTypeInterface> getInterfaces() { + return interfaces; + } - public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) { - this.interfaces = interfaces; - } + public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) { + this.interfaces = interfaces; + } - public String getIconPath() { - return iconPath; - } + public String getIconPath() { + return iconPath; + } - public void setIconPath(String iconPath) { - this.iconPath = iconPath; - } + public void setIconPath(String iconPath) { + this.iconPath = iconPath; + } - @Override - public String toString() { - return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; - } + @Override + public String toString() { + return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java index 25bab766bf..05fa3193c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java @@ -24,14 +24,14 @@ import java.util.List; public class ToscaNodeTypeInterface { - List<String> scripts; + List<String> scripts; - public List<String> getScripts() { - return scripts; - } + public List<String> getScripts() { + return scripts; + } - public void setScripts(List<String> scripts) { - this.scripts = scripts; - } + public void setScripts(List<String> scripts) { + this.scripts = scripts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 83cda6ef87..f895577c5d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -41,54 +41,53 @@ import org.slf4j.LoggerFactory; public class BEAppContextListener extends AppContextListener implements ServletContextListener { - private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; - private static Logger log = LoggerFactory.getLogger(BEAppContextListener.class.getName()); - - public void contextInitialized(ServletContextEvent context) { + private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; + private static final Logger log = LoggerFactory.getLogger(BEAppContextListener.class); - super.contextInitialized(context); + public void contextInitialized(ServletContextEvent context) { - ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); - log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName()); + super.contextInitialized(context); - context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); + ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); + log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName()); - WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper(); - context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper); + context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); - DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic(); - context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic); + WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper(); + context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper); - context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); + DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic(); + context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic); - // Monitoring service - BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); - bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); + context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); - log.debug("After executing {}", this.getClass()); + // Monitoring service + BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); + bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); - } - - private String getVersionFromManifest(ServletContextEvent context) { - ServletContext servletContext = context.getServletContext(); - InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); + log.debug("After executing {}", this.getClass()); - String version = null; - try { - Manifest mf = new Manifest(inputStream); - Attributes atts = mf.getMainAttributes(); - version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR); - if (version == null || version.isEmpty()) { - log.warn("failed to read ASDC version from MANIFEST."); - } else { - log.info("ASDC version from MANIFEST is {}", version); - } + } - } catch (IOException e) { - log.warn("failed to read ASDC version from MANIFEST", e.getMessage()); - } + private String getVersionFromManifest(ServletContextEvent context) { + ServletContext servletContext = context.getServletContext(); + InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); - return version; - } + String version = null; + try { + Manifest mf = new Manifest(inputStream); + Attributes atts = mf.getMainAttributes(); + version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR); + if (version == null || version.isEmpty()) { + log.warn("failed to read ASDC version from MANIFEST."); + } else { + log.info("ASDC version from MANIFEST is {}", version); + } + + } catch (IOException e) { + log.warn("failed to read ASDC version from MANIFEST", e); + } + return version; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java new file mode 100644 index 0000000000..216e55a2b1 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.mixin; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; +import org.openecomp.sdc.be.view.Mixin; +import org.openecomp.sdc.be.view.MixinTarget; + +@MixinTarget(target = GroupTypeDataDefinition.class) +public abstract class GroupTypeMixin extends Mixin { + + @JsonProperty + abstract String getType(); + @JsonProperty + abstract String getVersion(); + @JsonProperty + abstract String getUniqueId(); + +} + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java new file mode 100644 index 0000000000..0fd86e1ced --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.mixin; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; +import org.openecomp.sdc.be.view.Mixin; +import org.openecomp.sdc.be.view.MixinTarget; + +@MixinTarget(target = PolicyTypeDataDefinition.class) +public abstract class PolicyTypeMixin extends Mixin { + + @JsonProperty + abstract String getType(); + @JsonProperty + abstract String getVersion(); + @JsonProperty + abstract String getUniqueId(); + +} + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java index 6be300d6db..ba6596d1a2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.monitoring; -import java.net.URI; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.proxy.ProxyServlet; @@ -36,75 +30,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.net.URI; + public class EsGateway extends ProxyServlet { - private static final long serialVersionUID = 1L; - private static Logger log = LoggerFactory.getLogger(EsGateway.class.getName()); + private static final long serialVersionUID = 1L; + private static final Logger log = LoggerFactory.getLogger(EsGateway.class); - @Override - public URI rewriteURI(HttpServletRequest request) { + @Override + public URI rewriteURI(HttpServletRequest request) { - String originalUrl = request.getRequestURI(); + String originalUrl = request.getRequestURI(); - String redirectedUrl = getModifiedUrl(request); + String redirectedUrl = getModifiedUrl(request); - log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); - return URI.create(redirectedUrl); - } + log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); + return URI.create(redirectedUrl); + } - @Override - public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) { - super.customizeProxyRequest(proxyRequest, request); + @Override + public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) { + super.customizeProxyRequest(proxyRequest, request); - } + } - @Override - protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) { - super.onResponseSuccess(request, response, proxyResponse); - } + @Override + protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) { + super.onResponseSuccess(request, response, proxyResponse); + } - public String getModifiedUrl(HttpServletRequest request) { - String esHost = null; - String esPort = null; - MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext()); - if (monitoringBL == null) { - log.error("failed to retrive monitoringBL."); - } else { - esHost = monitoringBL.getEsHost(); - esPort = monitoringBL.getEsPort(); - } + public String getModifiedUrl(HttpServletRequest request) { + String esHost = null; + String esPort = null; + MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext()); + if (monitoringBL == null) { + log.error("failed to retrive monitoringBL."); + } else { + esHost = monitoringBL.getEsHost(); + esPort = monitoringBL.getEsPort(); + } - //String scheme = request.getScheme(); esGateway HTTP - String scheme = "http"; - String contextPath = request.getContextPath(); // /mywebapp - String servletPath = request.getServletPath(); // /servlet/MyServlet - String pathInfo = request.getPathInfo(); // /a/b;c=123 - String queryString = request.getQueryString(); // d=789 + //String scheme = request.getScheme(); esGateway HTTP + String scheme = "http"; + String contextPath = request.getContextPath(); // /mywebapp + String servletPath = request.getServletPath(); // /servlet/MyServlet + String pathInfo = request.getPathInfo(); // /a/b;c=123 + String queryString = request.getQueryString(); // d=789 - StringBuilder url = new StringBuilder(); - url.append(scheme).append("://").append(esHost); - url.append(":").append(esPort); - url.append(contextPath).append(servletPath); + StringBuilder url = new StringBuilder(); + url.append(scheme).append("://").append(esHost); + url.append(":").append(esPort); + url.append(contextPath).append(servletPath); - if (pathInfo != null) { - url.append(pathInfo); - } - if (queryString != null) { - url.append("?").append(queryString); - } + if (pathInfo != null) { + url.append(pathInfo); + } + if (queryString != null) { + url.append("?").append(queryString); + } - String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/"); - return redirectedUrl; + String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/"); + return redirectedUrl; - } + } - protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { + protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class); - return monitoringBusinessLogic; - } + return monitoringBusinessLogic; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index 1625b50bae..b67469d469 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -20,30 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; -import java.util.zip.ZipInputStream; - -import javax.annotation.Resource; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; import org.openecomp.sdc.be.components.impl.ImportUtils; @@ -67,870 +51,830 @@ import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.UploadArtifactInfo; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.YamlToObjectConverter; import org.openecomp.sdc.common.util.ZipUtil; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; - -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.zip.ZipInputStream; public abstract class AbstractValidationsServlet extends BeGenericServlet { - @Resource - private ServletUtils servletUtils; - - @Resource - private ResourceImportManager resourceImportManager; - - @Autowired - protected ComponentsUtils componentsUtils; - - private Logger log = null; - - protected void init(Logger log) { - initLog(log); - initSpringFromContext(); - - } - - protected synchronized void initLog(Logger log) { - if (this.log == null) { - this.log = log; - } - } - - private synchronized void initSpringFromContext() { - if (servletUtils == null) { - ServletContext context = servletRequest.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context - .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - servletUtils = webApplicationContext.getBean(ServletUtils.class); - resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); - } - } - - protected void validateResourceDoesNotExist(Wrapper<Response> responseWrapper, User user, String resourceName) { - if (resourceImportManager.isResourceExist(resourceName)) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) { - log.debug("get user {} from DB", userUserId); - // get user details - if (userUserId == null) { - log.info("user userId is null"); - Response response = returnMissingInformation(new User()); - responseWrapper.setInnerElement(response); - } - - else { - IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); - Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false); - if (eitherCreator.isRight()) { - log.info("user is not listed. userId={}", userUserId); - User user = new User(); - user.setUserId(userUserId); - Response response = returnMissingInformation(user); - responseWrapper.setInnerElement(response); - } else { - userWrapper.setInnerElement(eitherCreator.left().value()); - } - } - } - - protected Response returnMissingInformation(User user) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return buildErrorResponse(responseFormat); - } - - protected void validateDataNotNull(Wrapper<Response> responseWrapper, Object... dataParams) { - for (Object dataElement : dataParams) { - if (dataElement == null) { - log.info("Invalid body was received."); - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(response); - break; - } - } - - } - - protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user) { - log.debug("validate user role"); - if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) { - log.info("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - - Response response = buildErrorResponse(responseFormat); - errorResponseWrapper.setInnerElement(response); - } - - } - - protected void validateZip(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) { - log.info("Invalid json was received. payloadName should be yml file name"); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResponse); - } - - } - protected void validateCsar(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) { - log.info("Invalid json was received. payloadName should be yml file name"); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - String ymlName = unzippedFolder.keySet().iterator().next(); - fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); - } - - protected void fillToscaTemplateFromZip(Wrapper<String> yamlStringWrapper, String payloadName, File file) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - byte[] yamlFileInBytes = unzippedFolder.get(payloadName); - String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8); - log.debug("received yaml: {}", yamlAsString); - yamlStringWrapper.setInnerElement(yamlAsString); - } - - protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) { - try(InputStream fileInputStream = new FileInputStream(file);){ - - byte [] data = new byte[(int)file.length()]; - if( fileInputStream.read(data) == -1){ - log.info("Invalid json was received."); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - String payloadData = Base64.encodeBase64String(data); - uploadResourceInfoWrapper.setPayloadData(payloadData); - - - - } catch (IOException e) { - log.info("Invalid json was received or Error while closing input Stream."); - log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - - } - } - - protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) { - log.debug("validate user role"); - if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) { - if (!user.getRole().equals(Role.ADMIN.name())) { - log.info("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - - Response response = buildErrorResponse(responseFormat); - errorResponseWrapper.setInnerElement(response); - } - } else { - validateUserRole(errorResponseWrapper, user); - } - - } - - protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) { - boolean isValid; - try { - log.debug("The received json is {}", resourceInfo); - UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class); - if (resourceInfoObject == null) { - isValid = false; - } else { - if (!resourceAuthorityEnum.isBackEndImport()) { - isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); - //only resource name is checked - } else { - isValid = true; - } - uploadResourceInfoWrapper.setInnerElement(resourceInfoObject); - } - - } catch (JsonSyntaxException e) { - log.debug("Invalid json was received. {}", e.getMessage(), e); - isValid = false; - - } - if (!isValid) { - log.info("Invalid json was received."); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - } - - protected void validateAuthorityType(Wrapper<Response> responseWrapper, String authorityType) { - log.debug("The received authority type is {}", authorityType); - ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType); - if (authorityTypeEnum == null) { - log.info("Invalid authority type was received."); - Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResp); - } - } - - public ServletUtils getServletUtils() { - initSpringFromContext(); - return servletUtils; - } - - public Gson getGson() { - return getServletUtils().getGson(); - } - - public ComponentsUtils getComponentsUtils() { - return getServletUtils().getComponentsUtils(); - } - - protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { - log.debug("checking payload is valid tosca"); - boolean isValid; - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); - Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - - if (findFirstToscaStringElement.isRight()) { - isValid = false; - } else { - String defenitionVersionFound = findFirstToscaStringElement.left().value(); - if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { - isValid = false; - } else { - isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); - } - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) { - log.debug("checking tosca template is valid yml"); - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes()); - if (!isYamlValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) { - boolean isValid; - String nameSpace = ""; - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); - Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { - isValid = false; - } else { - nameSpace = toscaElement.left().value().keySet().iterator().next(); - isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - } - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } else { - String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = str1.split("\\."); - if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) { - String type = findTypes[0].toUpperCase(); - resourceInfo.setResourceType(type); - } else { - resourceInfo.setResourceType(ResourceTypeEnum.VFC.name()); - } - } - - } - - protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { - log.debug("checking payload contains single resource"); - boolean isValid; - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); - Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isRight()) { - isValid = false; - } else { - isValid = toscaElement.left().value().size() == 1; - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { - log.debug("checking payload is not a tosca service"); - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); - Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - - if (toscaElement.isLeft()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { - String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName(); - boolean isValidSuffix = false; - if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) { - for (String validSuffix : ImportUtils.Constants.TOSCA_YML_CSAR_VALID_SUFFIX) { - isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix); - } - } - if (!isValidSuffix) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) { - boolean isValid; - String recievedMD5 = request.getHeader(Constants.MD5_HEADER); - if (recievedMD5 == null) { - isValid = false; - } else { - String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString); - isValid = calculateMD5.equals(recievedMD5); - } - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validateComponentType(Wrapper<Response> responseWrapper, Wrapper<ComponentTypeEnum> componentWrapper, String componentType) { - boolean isValid; - if (componentType == null) { - isValid = false; - } else { - if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) { - isValid = true; - componentWrapper.setInnerElement(ComponentTypeEnum.RESOURCE); - } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) { - isValid = true; - componentWrapper.setInnerElement(ComponentTypeEnum.SERVICE); - } else { - isValid = false; - } - } - if (!isValid) { - log.debug("Invalid componentType:{}", componentType); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - } - - protected void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo resourceInfo) { - if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } else { - String toscaPayload = resourceInfo.getPayloadData(); - String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); - yamlStringWrapper.setInnerElement(decodedPayload); - } - - } - - protected void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, - File file) throws FileNotFoundException { - - if (responseWrapper.isEmpty()) { - if (resourceAuthorityEnum.isBackEndImport()) { - // PrePayload Validations - if (responseWrapper.isEmpty()) { - validateDataNotNull(responseWrapper, file, resourceInfoJsonString); - } - if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ - if (responseWrapper.isEmpty()) { - validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); - } - - // Fill PayLoad From File - if (responseWrapper.isEmpty()) { - fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); - } - }else{ - - if (responseWrapper.isEmpty()) { - validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); - } - - // Fill PayLoad From File - if (responseWrapper.isEmpty()) { - fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file); - } - - } - - } else { - // Fill PayLoad From JSON - if (responseWrapper.isEmpty()) { - fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement()); - } - } - - } - - } - - protected void specificResourceAuthorityValidations(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString, - ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException { - - if (responseWrapper.isEmpty()) { - // UI Only Validation - if (!resourceAuthorityEnum.isBackEndImport()) { - importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString); - } - - // User Defined Type Resources - if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { - if (responseWrapper.isEmpty()) { - validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); - } - - } - } - } - - protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId, - String resourceInfoJsonString) { - - if (responseWrapper.isEmpty()) { - validateUserExist(responseWrapper, userWrapper, userUserId); - } - - if (responseWrapper.isEmpty()) { - validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum); - } - - if (responseWrapper.isEmpty()) { - validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString); - } - - if (responseWrapper.isEmpty()) { - validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement(), resourceAuthorityEnum); - } - - } - - private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum) { - String resourceType = uploadResourceInfo.getResourceType(); - if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - if (resourceType.equals(ResourceTypeEnum.getTypeByName("VF").getValue()) && resourceAuthorityEnum == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE){ - log.debug("Import of VF resource type is forbidden - VF resource import can be done using onboarding flow only"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_TYPE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) { - if (responseWrapper.isEmpty()) { - validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString); - } - if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) { - validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName()); - } - } - - protected void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { - - if (responseWrapper.isEmpty()) { - validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - } - - /*protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { - - if (responseWrapper.isEmpty()) { - validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTopologyTemplate(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - - }*/ - - protected void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { - Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse; - Response response; - Object representation = null; - - if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) { - log.debug("import resource from csar"); - - createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId); - //if (createOrUpdateResponse.isLeft()){ - // LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - // lifecycleChangeInfo.setUserRemarks("certification on import"); - // Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceImportManager.getResourceBusinessLogic().validatePropertiesDefaultValues(createOrUpdateResponse.left().value().left); - //} - - } else if (!authority.isUserTypeResource()) { - log.debug("import normative type resource"); - createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); - } else { - log.debug("import user resource (not normative type)"); - createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false, false); - } - if (createOrUpdateResponse.isRight()) { - response = buildErrorResponse(createOrUpdateResponse.right().value()); - } else { - try { - representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft()); - } catch (IOException e) { - log.debug("Error while building resource representation : {}", e.getMessage(), e); - } - ActionStatus successStatus = createOrUpdateResponse.left().value().right; - response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation); - } - responseWrapper.setInnerElement(response); - } - - private Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { - - Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes; - ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null; - ActionStatus actionStatus; - org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); - String payloadName = resourceInfoObject.getPayloadName(); - fillResourceFromResourceInfoObject(resource, resourceInfoObject); - - Either<Map<String, byte[]>, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject); - if (csarUIPayloadRes.isRight()) { - return Either.right(csarUIPayloadRes.right().value()); - } - Map<String, byte[]> csarUIPayload = csarUIPayloadRes.left().value(); - - createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { - createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - actionStatus = ActionStatus.CREATED; - } else { - createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - actionStatus = ActionStatus.OK; - } - result = new ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>(createOrUpdateResourceRes.left().value(), actionStatus); - return Either.left(result); - } - - private Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) { - - Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils()); - - if (getToscaYamlRes.isRight()) { - ResponseFormat responseFormat = getToscaYamlRes.right().value(); - log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - getComponentsUtils().auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - String toscaYaml = getToscaYamlRes.left().value().getValue(); - - log.debug("checking tosca template is valid yml"); - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes()); - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - return Either.right(responseFormat); - } - - log.debug("checking payload is valid tosca"); - String heatDecodedPayload = toscaYaml; - Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload); - Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - - if (findFirstToscaStringElement.isRight()) { - isValid = false; - } else { - String defenitionVersionFound = findFirstToscaStringElement.left().value(); - if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { - isValid = false; - } else { - isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); - } - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - return Either.right(responseFormat); - } - return Either.left(resource); - } - - private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { - if (resource != null && resourceInfoObject != null) { - resource.setDescription(resourceInfoObject.getDescription()); - resource.setTags(resourceInfoObject.getTags()); - resource.setCategories(resourceInfoObject.getCategories()); - resource.setContactId(resourceInfoObject.getContactId()); - resource.setName(resourceInfoObject.getName()); - resource.setIcon(resourceInfoObject.getResourceIconPath()); - resource.setVendorName(resourceInfoObject.getVendorName()); - resource.setVendorRelease(resourceInfoObject.getVendorRelease()); - resource.setResourceType(ResourceTypeEnum.valueOf(resourceInfoObject.getResourceType())); - List<UploadArtifactInfo> artifactList = resourceInfoObject.getArtifactList(); - if (artifactList != null) { - Map<String, ArtifactDefinition> artifactsHM = new HashMap<String, ArtifactDefinition>(); - for (UploadArtifactInfo artifact : artifactList) { - ArtifactDefinition artifactDef = new ArtifactDefinition(); - artifactDef.setArtifactName(artifact.getArtifactName()); - artifactDef.setArtifactType(artifact.getArtifactType().getType()); - artifactDef.setDescription(artifact.getArtifactDescription()); - artifactDef.setPayloadData(artifact.getArtifactData()); - artifactDef.setArtifactRef(artifact.getArtifactPath()); - artifactsHM.put(artifactDef.getArtifactName(), artifactDef); - } - resource.setArtifacts(artifactsHM); - } - } - - } - - private Either<Map<String, byte[]>, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) { - String csarUUID = innerElement.getPayloadName(); - String payloadData = innerElement.getPayloadData(); - if (payloadData == null) { - log.info("Failed to decode received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); - } - - byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)); - if (decodedPayload == null) { - log.info("Failed to decode received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); - } - - Map<String, byte[]> csar = ZipUtil.readZip(decodedPayload); - if (csar == null) { - log.info("Failed to unzip received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - return Either.left(csar); - } - - protected void validateInputStream(final HttpServletRequest request, Wrapper<String> dataWrapper, Wrapper<ResponseFormat> errorWrapper) throws IOException { - InputStream inputStream = request.getInputStream(); - byte[] bytes = IOUtils.toByteArray(inputStream); - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8)); - } - - } - - protected <T> void validateClassParse(String data, Wrapper<T> parsedClassWrapper, Supplier<Class<T>> classGen, Wrapper<ResponseFormat> errorWrapper) { - try { - T parsedClass = gson.fromJson(data, classGen.get()); - if (parsedClass == null) { - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - parsedClassWrapper.setInnerElement(parsedClass); - } - } catch (JsonSyntaxException e) { - log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - - protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) { - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } else { - blWrapper.setInnerElement(componentInstanceLogic); - } - } - - protected <T> Response buildResponseFromElement(Wrapper<ResponseFormat> errorWrapper, Wrapper<T> attributeWrapper) throws IOException { - Response response; - if (errorWrapper.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(attributeWrapper.getInnerElement()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } else { - response = buildErrorResponse(errorWrapper.getInnerElement()); - } - return response; - } - - protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) { - ResponseFormat responseFormat; - if(StringUtils.isEmpty(instanceIdHeader) ){ - log.debug("Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(responseFormat); - } - } - - protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) { - ResponseFormat responseFormat; - if( StringUtils.isEmpty(header)){ - log.debug("MissingUSER_ID"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(responseFormat); - } - } - - /** - * Convert json to Object object - * @param <T> - * @param classSupplier - * @param json - * @return - */ - public <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) { - - try { - T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); - return Either.left(object); - } catch (Exception e) { - log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } - - /** - * Convert json to Object object - * @param <T> - * @param json - * @param type - * @return - */ - public <T> Either<List<T>, ResponseFormat> parseListOfObjects(String json, Type type) { - try { - List<T> listOfObjects = gson.fromJson(json, type); - return Either.left(listOfObjects); - } catch (Exception e) { - log.debug("Failed to parse json to {} object", type.getClass().getName(), e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } + private static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_"; + private static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1"); + private static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar"); + + protected ServletUtils servletUtils; + + protected ResourceImportManager resourceImportManager; + + protected ComponentsUtils componentsUtils; + + private Logger log = null; + + protected void init(Logger log) { + initLog(log); + initSpringFromContext(); + + } + + protected synchronized void initLog(Logger log) { + if (this.log == null) { + this.log = log; + } + } + + private synchronized void initSpringFromContext() { + if (servletUtils == null) { + ServletContext context = servletRequest.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + servletUtils = webApplicationContext.getBean(ServletUtils.class); + resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); + } + } + + protected void validateResourceDoesNotExist(Wrapper<Response> responseWrapper, User user, String resourceName) { + if (resourceImportManager.isResourceExist(resourceName)) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceName, AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) { + log.debug("get user {} from DB", userUserId); + // get user details + if (userUserId == null) { + log.info("user userId is null"); + Response response = returnMissingInformation(new User()); + responseWrapper.setInnerElement(response); + } + + else { + IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); + Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false); + if (eitherCreator.isRight()) { + log.info("user is not listed. userId={}", userUserId); + User user = new User(); + user.setUserId(userUserId); + Response response = returnMissingInformation(user); + responseWrapper.setInnerElement(response); + } else { + userWrapper.setInnerElement(eitherCreator.left().value()); + } + } + } + + protected Response returnMissingInformation(User user) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + return buildErrorResponse(responseFormat); + } + + protected void validateDataNotNull(Wrapper<Response> responseWrapper, Object... dataParams) { + for (Object dataElement : dataParams) { + if (dataElement == null) { + log.info("Invalid body was received."); + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(response); + break; + } + } + + } + + protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user) { + log.debug("validate user role"); + if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) { + log.info("user is not in appropriate role to perform action"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + + Response response = buildErrorResponse(responseFormat); + errorResponseWrapper.setInnerElement(response); + } + + } + + protected void validateZip(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) { + log.info("Invalid json was received. payloadName should be yml file name"); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResponse); + } + + } + protected void validateCsar(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) { + log.info("Invalid json was received. payloadName should be yml file name"); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + String ymlName = unzippedFolder.keySet().iterator().next(); + fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); + } + + protected void fillToscaTemplateFromZip(Wrapper<String> yamlStringWrapper, String payloadName, File file) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + byte[] yamlFileInBytes = unzippedFolder.get(payloadName); + String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8); + log.debug("received yaml: {}", yamlAsString); + yamlStringWrapper.setInnerElement(yamlAsString); + } + + protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) { + try(InputStream fileInputStream = new FileInputStream(file)){ + + byte [] data = new byte[(int)file.length()]; + if( fileInputStream.read(data) == -1){ + log.info("Invalid json was received."); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + } + String payloadData = Base64.encodeBase64String(data); + uploadResourceInfoWrapper.setPayloadData(payloadData); + + + + } catch (IOException e) { + log.info("Invalid json was received or Error while closing input Stream."); + log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + + } + } + + protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) { + log.debug("validate user role"); + if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) { + if (!user.getRole().equals(Role.ADMIN.name())) { + log.info("user is not in appropriate role to perform action"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + + Response response = buildErrorResponse(responseFormat); + errorResponseWrapper.setInnerElement(response); + } + } else { + validateUserRole(errorResponseWrapper, user); + } + + } + + protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) { + boolean isValid; + try { + log.debug("The received json is {}", resourceInfo); + UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class); + if (resourceInfoObject == null) { + isValid = false; + } else { + if (!resourceAuthorityEnum.isBackEndImport()) { + isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); + //only resource name is checked + } else { + isValid = true; + } + uploadResourceInfoWrapper.setInnerElement(resourceInfoObject); + } + + } catch (JsonSyntaxException e) { + log.debug("Invalid json was received. {}", e.getMessage(), e); + isValid = false; + + } + if (!isValid) { + log.info("Invalid json was received."); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + } + } + + protected void validateAuthorityType(Wrapper<Response> responseWrapper, String authorityType) { + log.debug("The received authority type is {}", authorityType); + ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType); + if (authorityTypeEnum == null) { + log.info("Invalid authority type was received."); + Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResp); + } + } + + public ServletUtils getServletUtils() { + initSpringFromContext(); + return servletUtils; + } + + public Gson getGson() { + return getServletUtils().getGson(); + } + + public ComponentsUtils getComponentsUtils() { + return getServletUtils().getComponentsUtils(); + } + + protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { + log.debug("checking payload is valid tosca"); + boolean isValid; + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); + Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); + + if (findFirstToscaStringElement.isRight()) { + isValid = false; + } else { + String defenitionVersionFound = findFirstToscaStringElement.left().value(); + if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { + isValid = false; + } else { + isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); + } + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) { + log.debug("checking tosca template is valid yml"); + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes()); + if (!isYamlValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) { + boolean isValid; + String nameSpace = ""; + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); + Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { + isValid = false; + } else { + nameSpace = toscaElement.left().value().keySet().iterator().next(); + isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + } + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } else { + String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = str1.split("\\."); + if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) { + String type = findTypes[0].toUpperCase(); + resourceInfo.setResourceType(type); + } else { + resourceInfo.setResourceType(ResourceTypeEnum.VFC.name()); + } + } + + } + + protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { + log.debug("checking payload contains single resource"); + boolean isValid; + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); + Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isRight()) { + isValid = false; + } else { + isValid = toscaElement.left().value().size() == 1; + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { + log.debug("checking payload is not a tosca service"); + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload); + Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); + + if (toscaElement.isLeft()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { + String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName(); + boolean isValidSuffix = false; + if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) { + for (String validSuffix : TOSCA_YML_CSAR_VALID_SUFFIX) { + isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix); + } + } + if (!isValidSuffix) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) { + boolean isValid; + String recievedMD5 = request.getHeader(Constants.MD5_HEADER); + if (recievedMD5 == null) { + isValid = false; + } else { + String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString); + isValid = calculateMD5.equals(recievedMD5); + } + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validateComponentType(Wrapper<Response> responseWrapper, Wrapper<ComponentTypeEnum> componentTypeWrapper, String componentType) { + boolean isValid; + if (componentType == null) { + isValid = false; + } else { + if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) { + isValid = true; + componentTypeWrapper.setInnerElement(ComponentTypeEnum.RESOURCE); + } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) { + isValid = true; + componentTypeWrapper.setInnerElement(ComponentTypeEnum.SERVICE); + } else { + isValid = false; + } + } + if (!isValid) { + log.debug("Invalid componentType:{}", componentType); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType))); + } + } + + protected Either<ComponentTypeEnum, ResponseFormat> convertToComponentType(String componentType) { + Wrapper<Response> errorWrapper = new Wrapper<>(); + Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<>(); + validateComponentType(errorWrapper, componentWrapper, componentType); + return errorWrapper.isEmpty() ? Either.left(componentWrapper.getInnerElement()) : Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + protected void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo resourceInfo) { + if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } else { + String toscaPayload = resourceInfo.getPayloadData(); + String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); + yamlStringWrapper.setInnerElement(decodedPayload); + } + + } + + protected void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, + File file) throws FileNotFoundException { + + if (responseWrapper.isEmpty()) { + if (resourceAuthorityEnum.isBackEndImport()) { + // PrePayload Validations + if (responseWrapper.isEmpty()) { + validateDataNotNull(responseWrapper, file, resourceInfoJsonString); + } + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + if (responseWrapper.isEmpty()) { + validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); + } + }else{ + + if (responseWrapper.isEmpty()) { + validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file); + } + + } + + } else { + // Fill PayLoad From JSON + if (responseWrapper.isEmpty()) { + fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement()); + } + } + + } + + } + + protected void specificResourceAuthorityValidations(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString, + ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException { + + if (responseWrapper.isEmpty()) { + // UI Only Validation + if (!resourceAuthorityEnum.isBackEndImport()) { + importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString); + } + + // User Defined Type Resources + if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { + if (responseWrapper.isEmpty()) { + validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); + } + + } + } + } + + protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId, + String resourceInfoJsonString) { + + if (responseWrapper.isEmpty()) { + validateUserExist(responseWrapper, userWrapper, userUserId); + } + + if (responseWrapper.isEmpty()) { + validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum); + } + + if (responseWrapper.isEmpty()) { + validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString); + } + + if (responseWrapper.isEmpty()) { + validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); + } + + } + + private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { + String resourceType = uploadResourceInfo.getResourceType(); + if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) { + if (responseWrapper.isEmpty()) { + validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString); + } + if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) { + validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName()); + } + } + + protected void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { + + if (responseWrapper.isEmpty()) { + validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); + } + } + + + protected void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { + Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse; + Response response; + Object representation = null; + + if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) { + log.debug("import resource from csar"); + + createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId); + } else if (!authority.isUserTypeResource()) { + log.debug("import normative type resource"); + createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); + } else { + log.debug("import user resource (not normative type)"); + createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false); + } + if (createOrUpdateResponse.isRight()) { + response = buildErrorResponse(createOrUpdateResponse.right().value()); + } else { + try { + representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft()); + } catch (IOException e) { + log.debug("Error while building resource representation : {}", e.getMessage(), e); + } + ActionStatus successStatus = createOrUpdateResponse.left().value().right; + response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation); + } + responseWrapper.setInnerElement(response); + } + + private Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { + + Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes; + ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null; + ActionStatus actionStatus; + org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); + String payloadName = resourceInfoObject.getPayloadName(); + fillResourceFromResourceInfoObject(resource, resourceInfoObject); + + Either<Map<String, byte[]>, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject); + if (csarUIPayloadRes.isRight()) { + return Either.right(csarUIPayloadRes.right().value()); + } + Map<String, byte[]> csarUIPayload = csarUIPayloadRes.left().value(); + + createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { + createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + actionStatus = ActionStatus.CREATED; + } else { + createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + actionStatus = ActionStatus.OK; + } + result = new ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>(createOrUpdateResourceRes.left().value(), actionStatus); + return Either.left(result); + } + + private Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) { + + Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils()); + + if (getToscaYamlRes.isRight()) { + ResponseFormat responseFormat = getToscaYamlRes.right().value(); + log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + String toscaYaml = getToscaYamlRes.left().value().getValue(); + + log.debug("checking tosca template is valid yml"); + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes()); + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + log.debug("checking payload is valid tosca"); + String heatDecodedPayload = toscaYaml; + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload); + Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); + + if (findFirstToscaStringElement.isRight()) { + isValid = false; + } else { + String defenitionVersionFound = findFirstToscaStringElement.left().value(); + if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { + isValid = false; + } else { + isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); + } + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + return Either.left(resource); + } + + private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { + resourceImportManager.populateResourceMetadata(resourceInfoObject, resource); + fillArtifacts(resource, resourceInfoObject); + + } + + private void fillArtifacts(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { + if (resource != null && resourceInfoObject != null) { + List<UploadArtifactInfo> artifactList = resourceInfoObject.getArtifactList(); + if (artifactList != null) { + Map<String, ArtifactDefinition> artifactsHM = new HashMap<String, ArtifactDefinition>(); + for (UploadArtifactInfo artifact : artifactList) { + ArtifactDefinition artifactDef = new ArtifactDefinition(); + artifactDef.setArtifactName(artifact.getArtifactName()); + artifactDef.setArtifactType(artifact.getArtifactType().getType()); + artifactDef.setDescription(artifact.getArtifactDescription()); + artifactDef.setPayloadData(artifact.getArtifactData()); + artifactDef.setArtifactRef(artifact.getArtifactPath()); + artifactsHM.put(artifactDef.getArtifactName(), artifactDef); + } + resource.setArtifacts(artifactsHM); + } + } + } + + private Either<Map<String, byte[]>, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) { + String csarUUID = innerElement.getPayloadName(); + String payloadData = innerElement.getPayloadData(); + if (payloadData == null) { + log.info("Failed to decode received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); + } + + byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)); + if (decodedPayload == null) { + log.info("Failed to decode received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); + } + + Map<String, byte[]> csar = ZipUtil.readZip(decodedPayload); + if (csar == null) { + log.info("Failed to unzip received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + return Either.left(csar); + } + + protected void validateInputStream(final HttpServletRequest request, Wrapper<String> dataWrapper, Wrapper<ResponseFormat> errorWrapper) throws IOException { + InputStream inputStream = request.getInputStream(); + byte[] bytes = IOUtils.toByteArray(inputStream); + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8)); + } + + } + + protected <T> void validateClassParse(String data, Wrapper<T> parsedClassWrapper, Supplier<Class<T>> classGen, Wrapper<ResponseFormat> errorWrapper) { + try { + T parsedClass = gson.fromJson(data, classGen.get()); + if (parsedClass == null) { + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + parsedClassWrapper.setInnerElement(parsedClass); + } + } catch (JsonSyntaxException e) { + log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + + protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) { + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } else { + blWrapper.setInnerElement(componentInstanceLogic); + } + } + + protected <T> Response buildResponseFromElement(Wrapper<ResponseFormat> errorWrapper, Wrapper<T> attributeWrapper) throws IOException { + Response response; + if (errorWrapper.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(attributeWrapper.getInnerElement()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } else { + response = buildErrorResponse(errorWrapper.getInnerElement()); + } + return response; + } + + protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) { + ResponseFormat responseFormat; + if(StringUtils.isEmpty(instanceIdHeader) ){ + log.debug("Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) { + ResponseFormat responseFormat; + if( StringUtils.isEmpty(header)){ + log.debug("MissingUSER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + /** + * Convert json to Object object + * @param <T> + * @param classSupplier + * @param json + * @return + */ + public <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) { + + try { + T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); + return Either.left(object); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } + + /** + * Convert json to Object object + * @param <T> + * @param json + * @param type + * @return + */ + public <T> Either<List<T>, ResponseFormat> parseListOfObjects(String json, Type type) { + try { + List<T> listOfObjects = gson.fromJson(json, type); + return Either.left(listOfObjects); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", type.getClass().getName(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java index ae103dbaca..f6d89e9065 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java @@ -20,22 +20,9 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,503 +37,496 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Additional Information Servlet", description = "Additional Information Servlet") @Singleton public class AdditionalInformationServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class.getName()); - - /** - * - * @param resourceId - * @param data - * @param request - * @param userUserId - * @return - */ - @POST - @Path("/resources/{resourceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data); - - } - - /** - * - * @param serviceId - * @param data - * @param request - * @param userUserId - * @return - */ - @POST - @Path("/services/{serviceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data); - - } - - /** - * - * @param resourceId - * @param labelId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data); - - } - - /** - * - * @param serviceId - * @param labelId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data); - - } - - /** - * - * @param resourceId - * @param labelId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); - - } - - /** - * - * @param serviceId - * @param labelId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); - - } - - /** - * - * @param resourceId - * @param labelId - * @param request - * @param userId - * @return - */ - @GET - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); - - } - - /** - * - * @param serviceId - * @param labelId - * @param request - * @param userId - * @return - */ - @GET - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); - - } - - /** - * - * @param resourceId - * @param request - * @param userId - * @return - */ - @GET - @Path("/resources/{resourceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId); - - } - - /** - * - * @param serviceId - * @param request - * @param userId - * @return - */ - @GET - @Path("/services/{serviceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId); - - } - - /** - * - * Create additional information property under given resource/service - * - * @param nodeType - * @param uniqueId - * @param request - * @param userId - * @param data - * @return - */ - protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); - - try { - // convert json to AdditionalInfoParameterInfo - AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); - - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); - - Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat); - return buildErrorResponse(responseFormat); - } - - AdditionalInfoParameterInfo createdAI = either.left().value(); - - log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createdAI); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Additional Information"); - log.debug("Create additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - - } - - /** - * Update additional information property by id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @param data - * @return - */ - protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); - - try { - // convert json to AdditionalInfoParameterInfo - AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); - - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); - - additionalInfoParameterInfo.setUniqueId(labelId); - - Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } - - AdditionalInfoParameterInfo createdAI = either.left().value(); - - log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + private static final Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class); + + /** + * + * @param resourceId + * @param data + * @param request + * @param userUserId + * @return + */ + @POST + @Path("/resources/{resourceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { + + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data); + + } + + /** + * + * @param serviceId + * @param data + * @param request + * @param userUserId + * @return + */ + @POST + @Path("/services/{serviceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { + + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data); + + } + + /** + * + * @param resourceId + * @param labelId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data); + + } + + /** + * + * @param serviceId + * @param labelId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data); + + } + + /** + * + * @param resourceId + * @param labelId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); + + } + + /** + * + * @param serviceId + * @param labelId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); + + } + + /** + * + * @param resourceId + * @param labelId + * @param request + * @param userId + * @return + */ + @GET + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); + + } + + /** + * + * @param serviceId + * @param labelId + * @param request + * @param userId + * @return + */ + @GET + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); + + } + + /** + * + * @param resourceId + * @param request + * @param userId + * @return + */ + @GET + @Path("/resources/{resourceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId); + + } + + /** + * + * @param serviceId + * @param request + * @param userId + * @return + */ + @GET + @Path("/services/{serviceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId); + + } + + /** + * + * Create additional information property under given resource/service + * + * @param nodeType + * @param uniqueId + * @param request + * @param userId + * @param data + * @return + */ + protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + log.debug("data is {}", data); + + try { + // convert json to AdditionalInfoParameterInfo + AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); + + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); + + Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat); + return buildErrorResponse(responseFormat); + } + + AdditionalInfoParameterInfo createdAI = either.left().value(); + + log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createdAI); + + } catch (Exception e) { + log.debug("Create additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + + } + + /** + * Update additional information property by id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @param data + * @return + */ + protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + log.debug("data is {}", data); + + try { + // convert json to AdditionalInfoParameterInfo + AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); + + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); + + additionalInfoParameterInfo.setUniqueId(labelId); + + Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } + + AdditionalInfoParameterInfo createdAI = either.left().value(); + + log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information"); - log.debug("Update additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information"); + log.debug("Update additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * - * Delete an additional information property by id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @return - */ - protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { + /** + * + * Delete an additional information property by id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @return + */ + protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - AdditionalInformationBusinessLogic businessLogic = getBL(context); + AdditionalInformationBusinessLogic businessLogic = getBL(context); - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setUniqueId(labelId); + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setUniqueId(labelId); - Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInfoParameterInfo createdAI = either.left().value(); + AdditionalInfoParameterInfo createdAI = either.left().value(); - log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information"); - log.debug("Delete additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information"); + log.debug("Delete additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * Get a specific additional information property by a given id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @return - */ - protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { + /** + * Get a specific additional information property by a given id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @return + */ + protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setUniqueId(labelId); + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setUniqueId(labelId); - Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInfoParameterInfo createdAI = either.left().value(); + AdditionalInfoParameterInfo createdAI = either.left().value(); - log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information"); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information"); - log.debug("get additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + log.debug("get additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * Get all additional information properties under given resource/service - * - * @param nodeType - * @param uniqueId - * @param request - * @param userId - * @return - */ - protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) { + /** + * Get all additional information properties under given resource/service + * + * @param nodeType + * @param uniqueId + * @param request + * @param userId + * @return + */ + protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - AdditionalInformationBusinessLogic businessLogic = getBL(context); + AdditionalInformationBusinessLogic businessLogic = getBL(context); - Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId); + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition); + log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, additionalInformationDefinition); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, additionalInformationDefinition); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information"); - log.debug("Get all addiotanl information properties failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information"); + log.debug("Get all addiotanl information properties failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - private AdditionalInformationBusinessLogic getBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class); - return bl; - } + private AdditionalInformationBusinessLogic getBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class); + return bl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java index 5a26b7c4e6..fa7ed4b547 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java @@ -20,23 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; @@ -52,15 +42,21 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; /** * Root resource (exposed at "/" path) */ @@ -70,535 +66,535 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ArtifactServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName()); - - // *************** Resources - @POST - @Path("/resources/{resourceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact"); - log.debug("loadArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact"); - log.debug("updateArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null); - } catch (Exception e) { - log.debug("deleteArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Services - @POST - @Path("/services/{serviceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact"); - log.debug("loadInformationArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact"); - log.debug("updateInformationArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Services api artifacts - @POST - @Path("/services/{serviceId}/artifacts/api/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact"); - log.debug("updateApiArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/services/{serviceId}/artifacts/api/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact"); - log.debug("deleteApiArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact"); - log.debug("deleteInformationalArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /* - * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href) - */ - - @GET - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") }) - public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); - log.debug("downloadServiceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); - log.debug("downloadResourceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") }) - public Response downloadResourceInstanceArtifactBase64( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Resource lifecycle ( interfces ) - - @POST - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Create, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); - log.debug("loadArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface"); - log.debug("deleteArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request, - @ApiParam(value = "json describe the artifact", required = true) String data) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Update, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); - log.debug("updateArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateRIArtifact( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); - log.debug("updateRIArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); - } catch (Exception e) { - log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Create, componentId, containerComponentType); - } catch (Exception e) { - log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); - } catch (Exception e) { - log.debug("deleteArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @GET - @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response getComponentArtifacts( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response getComponentInstanceArtifacts( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - // ////////// API END /////////////////////////// - - // ************ private ********************* - - private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.Create); - } - - private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update); - } - - private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); - - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - byte[] file = actionResult.left().value().getRight(); - String base64Contents = new String(Base64.encodeBase64(file)); - String artifactName = actionResult.left().value().getLeft(); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData(); - artifactUiDownloadData.setArtifactName(artifactName); - artifactUiDownloadData.setBase64Contents(base64Contents); - response = buildOkResponse(responseFormat, artifactUiDownloadData); - } - return response; - } - - private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE; - Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); - - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value()); - } - - return response; - } - - - private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { - return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null); - } - - private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.Delete), artifactId, null, null, null, interfaceType, operationName, - parentId, null); - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - Either<ArtifactDefinition, Operation> result = actionResult.left().value(); - if (result.isLeft()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); - } - } - return response; - - } - - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, - String containerComponentType) { - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, - artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, - containerComponentType); - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - Either<ArtifactDefinition, Operation> result = actionResult.left().value(); - if (result.isLeft()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); - } - } - return response; - - } - - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { - return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null); - } + private static final Logger log = LoggerFactory.getLogger(ArtifactServlet.class); + + // *************** Resources + @POST + @Path("/resources/{resourceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact"); + log.debug("loadArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact"); + log.debug("updateArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null); + } catch (Exception e) { + log.debug("deleteArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Services + @POST + @Path("/services/{serviceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact"); + log.debug("loadInformationArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact"); + log.debug("updateInformationArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Services api artifacts + @POST + @Path("/services/{serviceId}/artifacts/api/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact"); + log.debug("updateApiArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/services/{serviceId}/artifacts/api/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact"); + log.debug("deleteApiArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact"); + log.debug("deleteInformationalArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /* + * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href) + */ + + @GET + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") }) + public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); + log.debug("downloadServiceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); + log.debug("downloadResourceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") }) + public Response downloadResourceInstanceArtifactBase64( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Resource lifecycle ( interfces ) + + @POST + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); + log.debug("loadArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface"); + log.debug("deleteArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request, + @ApiParam(value = "json describe the artifact", required = true) String data) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); + log.debug("updateArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateRIArtifact( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); + log.debug("updateRIArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType); + } catch (Exception e) { + log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType); + } catch (Exception e) { + log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); + } catch (Exception e) { + log.debug("deleteArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @GET + @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentInstanceArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + // ////////// API END /////////////////////////// + + // ************ private ********************* + + private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) { + return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.CREATE); + } + + private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { + return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE); + } + + private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); + + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + byte[] file = actionResult.left().value().getRight(); + String base64Contents = new String(Base64.encodeBase64(file)); + String artifactName = actionResult.left().value().getLeft(); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData(); + artifactUiDownloadData.setArtifactName(artifactName); + artifactUiDownloadData.setBase64Contents(base64Contents); + response = buildOkResponse(responseFormat, artifactUiDownloadData); + } + return response; + } + + private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE; + Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); + + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value()); + } + + return response; + } + + + private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { + return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null); + } + + private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName, + parentId, null); + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + Either<ArtifactDefinition, Operation> result = actionResult.left().value(); + if (result.isLeft()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); + } + } + return response; + + } + + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, + String containerComponentType) { + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, + artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, + containerComponentType); + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + Either<ArtifactDefinition, Operation> result = actionResult.left().value(); + if (result.isLeft()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); + } + } + return response; + + } + + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { + return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index 1b02e0afa4..09ebb1cd31 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -20,21 +20,11 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -46,17 +36,13 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * Web Servlet for actions on Attributes * @@ -68,209 +54,209 @@ import io.swagger.annotations.ApiResponses; @Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet") @Singleton public class AttributeServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(AttributeServlet.class.getName()); - - /** - * Creates new Attribute on a resource with given resource ID - * - * @param resourceId - * @param data - * @param request - * @param userId - * @return - */ - @POST - @Path("resources/{resourceId}/attributes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource attribute already exist") }) - public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - - try { - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>(); - // convert json to AttributeDefinition - - buildAttributeFromString(data, attributesWrapper, errorWrapper); - if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); - if (createAttribute.isRight()) { - errorWrapper.setInnerElement(createAttribute.right().value()); - } else { - attributesWrapper.setInnerElement(createAttribute.left().value()); - } - } - - Response response; - if (!errorWrapper.isEmpty()) { - log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); - } else { - PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); - log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); - log.debug("create property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - /** - * Updates existing Attribute with given attributeID on a resource with given resourceID - * - * @param resourceId - * @param attributeId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("resources/{resourceId}/attributes/{attributeId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - try { - // convert json to PropertyDefinition - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>(); - // convert json to AttributeDefinition - - buildAttributeFromString(data, attributesWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); - // update property - if (eitherUpdateAttribute.isRight()) { - errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); - } else { - attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value()); - } - } - - Response response; - if (!errorWrapper.isEmpty()) { - log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); - } else { - PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); - log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); - log.debug("update attribute failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - /** - * Deletes existing Attribute with given attributeID on a resource with given resourceID - * - * @param resourceId - * @param attributeId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("resources/{resourceId}/attributes/{attributeId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - - try { - - // delete the property - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); - if (eitherAttribute.isRight()) { - log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); - return buildErrorResponse(eitherAttribute.right().value()); - } - PropertyDefinition attributeDefinition = eitherAttribute.left().value(); - String name = attributeDefinition.getName(); - - log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute"); - log.debug("delete attribute failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) { - - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); - if (attribute == null) { - log.info("Attribute content is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - errorWrapper.setInnerElement(responseFormat); - } else { - attributesWrapper.setInnerElement(attribute); - } - - } catch (Exception e) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - errorWrapper.setInnerElement(responseFormat); - log.debug("Attribute content is invalid - {}", data, e); - log.info("Attribute content is invalid - {}", data); - } - } + private static final Logger log = LoggerFactory.getLogger(AttributeServlet.class); + + /** + * Creates new Attribute on a resource with given resource ID + * + * @param resourceId + * @param data + * @param request + * @param userId + * @return + */ + @POST + @Path("resources/{resourceId}/attributes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource attribute already exist") }) + public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + + try { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>(); + // convert json to AttributeDefinition + + buildAttributeFromString(data, attributesWrapper, errorWrapper); + if (errorWrapper.isEmpty()) { + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); + if (createAttribute.isRight()) { + errorWrapper.setInnerElement(createAttribute.right().value()); + } else { + attributesWrapper.setInnerElement(createAttribute.left().value()); + } + } + + Response response; + if (!errorWrapper.isEmpty()) { + log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); + response = buildErrorResponse(errorWrapper.getInnerElement()); + } else { + PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); + log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); + log.debug("create property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + /** + * Updates existing Attribute with given attributeID on a resource with given resourceID + * + * @param resourceId + * @param attributeId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("resources/{resourceId}/attributes/{attributeId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + try { + // convert json to PropertyDefinition + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>(); + // convert json to AttributeDefinition + + buildAttributeFromString(data, attributesWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); + // update property + if (eitherUpdateAttribute.isRight()) { + errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); + } else { + attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value()); + } + } + + Response response; + if (!errorWrapper.isEmpty()) { + log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); + response = buildErrorResponse(errorWrapper.getInnerElement()); + } else { + PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); + log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); + log.debug("update attribute failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + /** + * Deletes existing Attribute with given attributeID on a resource with given resourceID + * + * @param resourceId + * @param attributeId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("resources/{resourceId}/attributes/{attributeId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + + try { + + // delete the property + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + if (eitherAttribute.isRight()) { + log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); + return buildErrorResponse(eitherAttribute.right().value()); + } + PropertyDefinition attributeDefinition = eitherAttribute.left().value(); + String name = attributeDefinition.getName(); + + log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute"); + log.debug("delete attribute failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) { + + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); + if (attribute == null) { + log.info("Attribute content is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + errorWrapper.setInnerElement(responseFormat); + } else { + attributesWrapper.setInnerElement(attribute); + } + + } catch (Exception e) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + errorWrapper.setInnerElement(responseFormat); + log.debug("Attribute content is invalid - {}", data, e); + log.info("Attribute content is invalid - {}", data); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 7407a4dff3..0e0d20ffcb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,30 +20,24 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Supplier; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - -import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import fj.data.Either; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; -import org.openecomp.sdc.be.components.impl.ProductComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.api.IElementDAO; @@ -51,204 +45,244 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.servlets.BasicServlet; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Supplier; public class BeGenericServlet extends BasicServlet { - @Context - protected HttpServletRequest servletRequest; - - private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName()); - - /******************** New error response mechanism - * @param additionalParams **************/ - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - } - - protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { - return buildOkResponse(errorResponseWrapper, entity, null); - } - - protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) { - int status = errorResponseWrapper.getStatus(); - ResponseBuilder responseBuilder = Response.status(status); - if (entity != null) { - if (log.isTraceEnabled()) - log.trace("returned entity is {}", entity.toString()); - responseBuilder = responseBuilder.entity(entity); - } - if (additionalHeaders != null) { - for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) { - String headerName = additionalHeader.getKey(); - String headerValue = additionalHeader.getValue(); - if (log.isTraceEnabled()) - log.trace("Adding header {} with value {} to the response", headerName, headerValue); - responseBuilder.header(headerName, headerValue); - } - } - return responseBuilder.build(); - } - - /*******************************************************************************************************/ - protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) { - Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); - if (eitherCreator.isRight()) { - log.info("createResource method - user is not listed. userId= {}", userId); - ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); - User user = new User("", "", userId, "", null, null); - - getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); - return Either.right(errorResponse); - } - return Either.left(eitherCreator.left().value()); - - } - - protected UserBusinessLogic getUserAdminManager(ServletContext context) { - return getClassFromWebAppContext(context, () -> UserBusinessLogic.class); - } - - protected ResourceBusinessLogic getResourceBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class); - } - - protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class); - } - - protected ServiceBusinessLogic getServiceBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class); - } - - protected ProductBusinessLogic getProductBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class); - } - - protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class); - } - - protected ElementBusinessLogic getElementBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class); - } - - protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class); - } - - protected AssetMetadataConverter getAssetUtils(ServletContext context) { - return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class); - } - - protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class); - } - - protected <SomeClass> SomeClass getClassFromWebAppContext(ServletContext context, Supplier<Class<SomeClass>> businessLogicClassGen) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get()); - return monitoringBusinessLogic; - } - - protected GroupBusinessLogic getGroupBL(ServletContext context) { - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - GroupBusinessLogic groupBusinessLogic = webApplicationContext.getBean(GroupBusinessLogic.class); - return groupBusinessLogic; - } - - protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - if (containerComponentType == ComponentTypeEnum.RESOURCE) { - return webApplicationContext.getBean(VFComponentInstanceBusinessLogic.class); - } - if (containerComponentType == ComponentTypeEnum.SERVICE) { - return webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class); - } - if (containerComponentType == ComponentTypeEnum.PRODUCT) { - return webApplicationContext.getBean(ProductComponentInstanceBusinessLogic.class); - } - return null; - } - - protected IElementDAO getElementDao(Class<? extends IElementDAO> clazz, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(clazz); - } - - protected ComponentsUtils getComponentsUtils() { - ServletContext context = this.servletRequest.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - /** - * Used to support Unit Test.<br> - * Header Params are not supported in Unit Tests - * - * @return - */ - protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) { - String retValue; - if (headerValue != null) { - retValue = headerValue; - } else { - retValue = request.getHeader(headerName); - } - return retValue; - } - - protected String getContentDispositionValue(String artifactFileName) { - return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString(); - } - - protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) { - ComponentBusinessLogic businessLogic; - switch (componentTypeEnum) { - case RESOURCE: { - businessLogic = getResourceBL(context); - break; - } - case SERVICE: { - businessLogic = getServiceBL(context); - break; - } - case PRODUCT: { - businessLogic = getProductBL(context); - break; - } - case RESOURCE_INSTANCE: { - businessLogic = getResourceBL(context); - break; - } - default: { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); - BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL"); - throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); - } - } - return businessLogic; - } + @Context + protected HttpServletRequest servletRequest; + + private static final Logger log = LoggerFactory.getLogger(BeGenericServlet.class); + + /******************** New error response mechanism + * @param requestErrorWrapper **************/ + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { + return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + } + + protected Response buildGeneralErrorResponse() { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + protected Response buildOkResponse(Object entity) { + return buildOkResponseStatic(entity); + } + + static public Response buildOkResponseStatic(Object entity) { + return Response.status(Response.Status.OK) + .entity(entity) + .build(); + } + + protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { + return buildOkResponse(errorResponseWrapper, entity, null); + } + + protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) { + int status = errorResponseWrapper.getStatus(); + ResponseBuilder responseBuilder = Response.status(status); + if (entity != null) { + if (log.isTraceEnabled()) + log.trace("returned entity is {}", entity.toString()); + responseBuilder = responseBuilder.entity(entity); + } + if (additionalHeaders != null) { + for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) { + String headerName = additionalHeader.getKey(); + String headerValue = additionalHeader.getValue(); + if (log.isTraceEnabled()) + log.trace("Adding header {} with value {} to the response", headerName, headerValue); + responseBuilder.header(headerName, headerValue); + } + } + return responseBuilder.build(); + } + + /*******************************************************************************************************/ + protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) { + Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); + if (eitherCreator.isRight()) { + log.info("createResource method - user is not listed. userId= {}", userId); + ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); + User user = new User("", "", userId, "", null, null); + + getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(errorResponse); + } + return Either.left(eitherCreator.left().value()); + + } + + protected PolicyTypeBusinessLogic getPolicyTypeBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> PolicyTypeBusinessLogic.class); + } + + protected UserBusinessLogic getUserAdminManager(ServletContext context) { + return getClassFromWebAppContext(context, () -> UserBusinessLogic.class); + } + + protected ResourceBusinessLogic getResourceBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class); + } + + protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class); + } + + protected ServiceBusinessLogic getServiceBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class); + } + + protected ProductBusinessLogic getProductBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class); + } + + protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class); + } + + protected ElementBusinessLogic getElementBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class); + } + + protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class); + } + + protected AssetMetadataConverter getAssetUtils(ServletContext context) { + return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class); + } + + protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class); + } + + protected PolicyBusinessLogic getPolicyBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> PolicyBusinessLogic.class); + } + + protected <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(businessLogicClassGen.get()); + } + + protected GroupBusinessLogic getGroupBL(ServletContext context) { + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(GroupBusinessLogic.class); + } + + protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentInstanceBusinessLogic.class); + } + + protected IElementDAO getElementDao(Class<? extends IElementDAO> clazz, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(clazz); + } + + protected ComponentsUtils getComponentsUtils() { + ServletContext context = this.servletRequest.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentsUtils.class); + } + + /** + * Used to support Unit Test.<br> + * Header Params are not supported in Unit Tests + * + * @return + */ + protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) { + String retValue; + if (headerValue != null) { + retValue = headerValue; + } else { + retValue = request.getHeader(headerName); + } + return retValue; + } + + protected String getContentDispositionValue(String artifactFileName) { + return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString(); + } + + protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) { + ComponentBusinessLogic businessLogic; + switch (componentTypeEnum) { + case RESOURCE: + businessLogic = getResourceBL(context); + break; + case SERVICE: + businessLogic = getServiceBL(context); + break; + case PRODUCT: + businessLogic = getProductBL(context); + break; + case RESOURCE_INSTANCE: + businessLogic = getResourceBL(context); + break; + default: + BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL"); + throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); + } + return businessLogic; + } + + protected <T> void convertJsonToObjectOfClass(String json, Wrapper<T> policyWrapper, Class<T> clazz, Wrapper<Response> errorWrapper) { + T object = null; + ObjectMapper mapper = new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + try { + log.trace("Starting to convert json to object. Json=\n{}", json); + + SimpleModule module = new SimpleModule("customDeserializationModule"); + module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer()); + mapper.registerModule(module); + + object = mapper.readValue(json, clazz); + if (object != null) { + policyWrapper.setInnerElement(object); + } else { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("The object of class {} is null after converting from json. ", clazz); + errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("The exception {} occured upon json to object convertation. Json=\n{}", e, json); + errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java index 81f1775a01..aa10ce0dd4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java @@ -20,22 +20,16 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.lang3.tuple.Pair; -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,139 +44,135 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) @Path("/") @Api(value = "BE Monitoring", description = "BE Monitoring") @Singleton public class BeMonitoringServlet extends BeGenericServlet { - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); - - @GET - @Path("/healthCheck") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") }) - public Response getHealthCheck(@Context final HttpServletRequest request) { - try { - HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext()); - Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); - Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft(); - ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR; - String sdcVersion = getVersionFromContext(request); - if (sdcVersion == null || sdcVersion.isEmpty()) { - sdcVersion = "UNKNOWN"; - } - String siteMode = healthCheckBusinessLogic.getSiteMode(); - HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode); - // The response can be either with 200 or 500 aggregate status - the - // body of individual statuses is returned either way - - String healthCheckStr = prettyGson.toJson(healthCheck); - return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, "BeHealthCheck"); - BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck"); - log.debug("BE health check unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/monitoring") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) { - try { - MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class); - if (monitoringEvent == null) { - return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); - } - log.trace("Received monitoring metrics: {}", monitoringEvent.toString()); - ServletContext context = request.getSession().getServletContext(); - MonitoringBusinessLogic bl = getMonitoringBL(context); - Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent); - if (result.isRight()) { - return buildErrorResponse(result.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - - } catch (Exception e) { - log.debug("BE system metrics unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/version") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") }) - public Response getSdcVersion(@Context final HttpServletRequest request) { - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - String version = getVersionFromContext(request); - log.debug("asdc version from manifest is: {}", version); - if (version == null || version.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND)); - } - - HealthCheckInfo versionInfo = new HealthCheckInfo(); - versionInfo.setVersion(version); - - // The response can be either with 200 or 500 aggregate status - the - // body of individual statuses is returned either way - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); - log.debug("BE get ASDC version unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private String getVersionFromContext(HttpServletRequest request) { - ServletContext servletContext = request.getSession().getServletContext(); - String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); - return version; - } - - protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) { - - MonitoringEvent object = null; - try { - object = gson.fromJson(content, clazz); - object.setFields(null); - } catch (Exception e) { - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return object; - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class); + + @GET + @Path("/healthCheck") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") }) + public Response getHealthCheck(@Context final HttpServletRequest request) { + try { + HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext()); + Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); + Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft(); + ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR; + String sdcVersion = getVersionFromContext(request); + if (sdcVersion == null || sdcVersion.isEmpty()) { + sdcVersion = "UNKNOWN"; + } + String siteMode = healthCheckBusinessLogic.getSiteMode(); + HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode); + // The response can be either with 200 or 500 aggregate status - the + // body of individual statuses is returned either way + + String healthCheckStr = prettyGson.toJson(healthCheck); + return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck"); + log.debug("BE health check unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/monitoring") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) { + try { + MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class); + if (monitoringEvent == null) { + return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); + } + log.trace("Received monitoring metrics: {}", monitoringEvent); + ServletContext context = request.getSession().getServletContext(); + MonitoringBusinessLogic bl = getMonitoringBL(context); + Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent); + if (result.isRight()) { + return buildErrorResponse(result.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + + } catch (Exception e) { + log.debug("BE system metrics unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/version") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") }) + public Response getSdcVersion(@Context final HttpServletRequest request) { + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + String version = getVersionFromContext(request); + log.debug("asdc version from manifest is: {}", version); + if (version == null || version.isEmpty()) { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND)); + } + + HealthCheckInfo versionInfo = new HealthCheckInfo(); + versionInfo.setVersion(version); + + // The response can be either with 200 or 500 aggregate status - the + // body of individual statuses is returned either way + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); + log.debug("BE get ASDC version unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private String getVersionFromContext(HttpServletRequest request) { + ServletContext servletContext = request.getSession().getServletContext(); + String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); + return version; + } + + protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) { + + MonitoringEvent object = null; + try { + object = gson.fromJson(content, clazz); + object.setFields(null); + } catch (Exception e) { + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return object; + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java new file mode 100644 index 0000000000..8ed68fa032 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.servlets; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class ComponentExceptionMapper implements ExceptionMapper<ComponentException> { + + private final ComponentsUtils componentsUtils; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public ComponentExceptionMapper(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @Override + public Response toResponse(ComponentException componentException) { + ResponseFormat responseFormat = componentException.getResponseFormat(); + if (componentException.getResponseFormat()==null) { + responseFormat = componentsUtils.getResponseFormat(componentException.getActionStatus(), componentException.getParams()); + } + + return Response.status(responseFormat.getStatus()) + .entity(gson.toJson(responseFormat.getRequestError())) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index b5971670cf..536fdc3c7e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -20,36 +20,26 @@ package org.openecomp.sdc.be.servlets; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; -import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.ForwardingPaths; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.ComponentInstance; @@ -60,24 +50,34 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; /** * Root resource (exposed at "/" path) .json @@ -88,845 +88,818 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ComponentInstanceServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class.getName()); - - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Component instance already exist") }) - public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - try { - - ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); - componentInstance.setInvariantName(null); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); - log.debug("create component instance failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - log.debug("Start handle request of {}", url); - - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); - - if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - ComponentInstance resourceInstance = convertResponse.left().value(); - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - log.debug("Start handle request of {}", url); - - if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) { - log.info("Empty JSON list was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray); - - if (convertResponse.isRight()) { - // Using both ECOMP error methods, show to Sofer - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - List<ComponentInstance> componentInstanceList = convertResponse.left().value(); - - Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - /* - * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeRestApiGeneralError, "Update Resource Instance" ); - */ - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - Response response = null; - try { - log.debug("Start handle request of {}", url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - String userId = request.getHeader(Constants.USER_ID_HEADER); - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); - log.debug("delete resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/associate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Relationship already exist") }) - public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - - try { - - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data); - - Either<RequirementCapabilityRelDef, ResponseFormat> resultOp; - if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI"); - log.debug("Failed to convert received data to BE format."); - resultOp = Either.right(regInfoW.right().value()); - } else { - RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); - resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp; - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); - log.debug("associate resource instance to another RI with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @PUT - @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response dissociateRIFromRI( - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data); - if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(regInfoW.right().value()); - } - - RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); - log.debug("dissociate resource instance from service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Relationship already exist") }) - public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - log.debug("Start handle request of {}", url); - - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class); - if (convertStatus.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI"); - log.debug("Failed to convert received data to BE format."); - Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); - return buildErrorResponse(formattedResponse.right().value()); - } - - CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value(); - Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance"); - log.debug("create and associate RI failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper<String> dataWrapper = new Wrapper<>(); - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (!errorWrapper.isEmpty()) { - return buildErrorResponse(errorWrapper.getInnerElement()); - } - - ComponentInstanceProperty property = propertyWrapper.getInnerElement(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertyValue(componentTypeEnum, componentId, componentInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper<String> dataWrapper = new Wrapper<>(); - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - ComponentInstanceInput property = null; - - if (errorWrapper.isEmpty()) { - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either<ComponentInstanceInput, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, - ComponentTypeEnum.SERVICE); - ; - if (inputEither.isRight()) { - log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - property = inputEither.left().value(); - - } - - if (property == null) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<ComponentInstanceInput, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - /** - * Updates ResourceInstance Attribute - * - * @param componentId - * @param containerComponentType - * @param componentInstanceId - * @param userId - * @param request - * @return - */ - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Wrapper<String> dataWrapper = new Wrapper<>(); - Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>(); - Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); - Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); - if (eitherAttribute.isRight()) { - errorWrapper.setInnerElement(eitherAttribute.right().value()); - } else { - attributeWrapper.setInnerElement(eitherAttribute.left().value()); - } - } - - return buildResponseFromElement(errorWrapper, attributeWrapper); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); - - if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - ComponentInstance newResourceInstance = convertResponse.left().value(); - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper<String> dataWrapper = new Wrapper<>(); - Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); - Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (!errorWrapper.isEmpty()) { - return buildErrorResponse(errorWrapper.getInnerElement()); - } - - ComponentInstanceProperty property = propertyWrapper.getInnerElement(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) - public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - - GroupBusinessLogic businessLogic = this.getGroupBL(context); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", containerComponentType); - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - // US831698 - @GET - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") }) - public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); - - Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); - - if (componentInstancePropertiesById.isRight()) { - log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); - return buildErrorResponse(componentInstancePropertiesById.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - // US330353 - @GET - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) - public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); - - Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, - capabilityType, capabilityName, userId); - - if (componentInstancePropertiesById.isRight()) { - log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); - return buildErrorResponse(componentInstancePropertiesById.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class); - private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) { - if (StringUtils.isEmpty(dataList)) { - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Component instance already exist") }) + public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + try { + + ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); + componentInstance.setInvariantName(null); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); + log.debug("create component instance failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + log.debug("Start handle request of {}", url); + + InputStream inputStream = request.getInputStream(); + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); + + if (convertResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + ComponentInstance resourceInstance = convertResponse.left().value(); + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return Either.left(Arrays.asList(convertStatus.left().value())); + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + log.debug("Start handle request of {}", url); + + if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) { + log.info("Empty JSON list was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray); + + if (convertResponse.isRight()) { + // Using both ECOMP error methods, show to Sofer + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + List<ComponentInstance> componentInstanceList = convertResponse.left().value(); + + Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + Response response = null; + try { + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + String userId = request.getHeader(Constants.USER_ID_HEADER); + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); + log.debug("delete resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/associate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Relationship already exist") }) + public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + + try { + + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data); + + Either<RequirementCapabilityRelDef, ResponseFormat> resultOp; + if (regInfoW.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI"); + log.debug("Failed to convert received data to BE format."); + resultOp = Either.right(regInfoW.right().value()); + } else { + RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); + resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); + } + + Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp; + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); + log.debug("associate resource instance to another RI with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @PUT + @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response dissociateRIFromRI( + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data); + if (regInfoW.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(regInfoW.right().value()); + } + + RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); + Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); + log.debug("dissociate resource instance from service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Relationship already exist") }) + public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + log.debug("Start handle request of {}", url); + + InputStream inputStream = request.getInputStream(); + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class); + if (convertStatus.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI"); + log.debug("Failed to convert received data to BE format."); + Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); + return buildErrorResponse(formattedResponse.right().value()); + } + + CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value(); + Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance"); + log.debug("create and associate RI failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceProperties(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>(); + if (errorWrapper.isEmpty()) { + Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray); + if (propertiesToUpdateEither.isRight()) { + errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); + } else { + propertiesToUpdate = propertiesToUpdateEither.left().value(); + } + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", propertiesToUpdate); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + List<ComponentInstanceProperty> resourceInstanceProperties = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperties); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + List<ComponentInstanceInput> inputsToUpdate = new ArrayList<>(); + if (errorWrapper.isEmpty()) { + Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray); + if (inputsToUpdateEither.isRight()) { + errorWrapper.setInnerElement(inputsToUpdateEither.right().value()); + } else { + inputsToUpdate = inputsToUpdateEither.left().value(); + } + } + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", inputsToUpdate); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse = + componentInstanceLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + List<ComponentInstanceInput> resourceInstanceInput = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceInput); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + /** + * Updates ResourceInstance Attribute + * + * @param componentId + * @param containerComponentType + * @param componentInstanceId + * @param userId + * @param request + * @return + */ + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Wrapper<String> dataWrapper = new Wrapper<>(); + Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>(); + Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); + Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); + if (eitherAttribute.isRight()) { + errorWrapper.setInnerElement(eitherAttribute.right().value()); + } else { + attributeWrapper.setInnerElement(eitherAttribute.left().value()); + } + } + + return buildResponseFromElement(errorWrapper, attributeWrapper); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try ( InputStream inputStream = request.getInputStream()) { + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); + + if (convertResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + ComponentInstance newResourceInstance = convertResponse.left().value(); + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper<String> dataWrapper = new Wrapper<>(); + Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); + Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + ComponentInstanceProperty property = propertyWrapper.getInnerElement(); + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) + public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", containerComponentType); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + // US831698 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") }) + public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); + + if (componentInstancePropertiesById.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(componentInstancePropertiesById.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + // US330353 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) + public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, + capabilityType, capabilityName, ownerId, userId); + + if (componentInstancePropertiesById.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(componentInstancePropertiesById.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } //US 331281 @PUT - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update Instance Capabilty Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, - @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId, + @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(PUT) Start handle request of {}", url); @@ -964,208 +937,282 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } } - @POST - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Service proxy already exist") }) - public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - try { - - ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); - componentInstance.setInvariantName(null); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.debug("Unsupported container component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy"); - log.debug("Create service proxy failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - Response response = null; - try { - log.debug("Start handle request of {}", url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - String userId = request.getHeader(Constants.USER_ID_HEADER); - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy"); - log.debug("Delete service proxy failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version"); - log.debug("Update service proxy with new version failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - /** - * REST API GET relation by Id - * Allows to get relation contained in specified component according to received Id - * @param containerComponentType - * @param componentId - * @param relationId - * @param request - * @param userId - * @return Response - */ - @GET - @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") }) - public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, - @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById"); - log.debug("getRelationById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) { - - Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); - } - ComponentInstance resourceInstanceInfo = convertStatus.left().value(); - - return Either.left(resourceInstanceInfo); - } - - private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) { - - Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); - } - - return Either.left(Arrays.asList(convertStatus.left().value())); - } - - private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) { - - Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class); - if (convertStatus.isRight()) { - return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); - } - RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value(); - return Either.left(requirementCapabilityRelDef); - } - - private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) { - try { - log.trace("convert json to object. json=\n {}", data); - T t = null; - t = gson.fromJson(data, clazz); - if (t == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(t); - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } + @POST + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Service proxy already exist") }) + public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + try { + + ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); + componentInstance.setInvariantName(null); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { + log.debug("Unsupported container component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy"); + log.debug("Create service proxy failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + Response response = null; + try { + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + String userId = request.getHeader(Constants.USER_ID_HEADER); + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy"); + log.debug("Delete service proxy failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version"); + log.debug("Update service proxy with new version failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + /** + * REST API GET relation by Id + * Allows to get relation contained in specified component according to received Id + * @param containerComponentType + * @param componentId + * @param relationId + * @param request + * @param userId + * @return Response + */ + @GET + @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") }) + public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, + @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + if (componentTypeEnum == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + + Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById"); + log.debug("getRelationById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) { + + // Either<ComponentInstance, ActionStatus> convertStatus = + // convertJsonToObject(data, ComponentInstance.class); + Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + ComponentInstance resourceInstanceInfo = convertStatus.left().value(); + + return Either.left(resourceInstanceInfo); + } + + private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) { + + Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) { + if (StringUtils.isEmpty(dataList)) { + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + private Either<List<ComponentInstanceInput>, ResponseFormat> convertMultipleInputs(String dataList) { + if (StringUtils.isEmpty(dataList)) { + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + + private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) { + + Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class); + if (convertStatus.isRight()) { + return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); + } + RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value(); + return Either.left(requirementCapabilityRelDef); + } + + private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) { + try { + log.trace("convert json to object. json=\n {}", data); + T t; + t = gson.fromJson(data, clazz); + if (t == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(t); + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } + + + @GET + @Path("/{containerComponentType}/{componentId}/paths-to-delete") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Check if forwarding path to delete on version change", httpMethod = "GET", notes = "Returns forwarding paths to delete", + response = Response.class) + public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId, + @QueryParam("componentInstanceId") final String oldComponentInstanceId, + @QueryParam("newComponentInstanceId") final String newComponentInstanceId, + @ApiParam(value = "valid values: resources / services", + allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) + @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + if (oldComponentInstanceId == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE)); + } + if (newComponentInstanceId == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE)); + } + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstance newComponentInstance; + if(StringUtils.isNotEmpty(newComponentInstanceId)){ + newComponentInstance=new ComponentInstance(); + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId); + }else{ + log.error("missing component id"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA)); + } + Either<Set<String>,ResponseFormat> actionResponse= componentInstanceLogic.forwardingPathOnVersionChange( + containerComponentType,componentId,oldComponentInstanceId,newComponentInstance); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + ForwardingPaths forwardingPaths=new ForwardingPaths(); + forwardingPaths.setForwardingPathToDelete(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths); + + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java index 0c955f4e5a..16fa67e7cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java @@ -20,26 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -59,345 +46,354 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Component Servlet", description = "Component Servlet") @Singleton public class ComponentServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName()); - - @GET - @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - Response response; - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum != null) { - ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); - if (eitherConformanceLevel.isRight()) { - response = buildErrorResponse(eitherConformanceLevel.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); - } - } else { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return response; - } - - @GET - @Path("/{componentType}/{componentId}/requirmentsCapabilities") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - Response response; - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum != null) { - try { - ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); - if (eitherRequirementsAndCapabilities.isRight()) { - response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value())); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); - log.debug("getRequirementAndCapabilities failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } else { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return response; - } - - @GET - @Path("/{componentType}/latestversion/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); - - Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @POST - @Path("/{componentType}/latestversion/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - List<String> componentUids = data; - if (log.isDebugEnabled()) - log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size())); - - Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); - - if (actionResponse.isRight()) { - if (log.isDebugEnabled()) - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - return responseToReturn; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @GET - @Path("/{componentType}/latestversion/notabstract/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @GET - @Path("/{componentType}/{componentId}/componentInstances") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText); - if (actionResponse.isRight()) { - log.debug("failed to get all component instances filtered by properties and inputs", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType); - log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - - - /** - * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. - * for example: list of the string "properties, inputs" will return component with the list of properties and inputs. - * - * @param componentType - * @param componentId - * @param dataParamsToReturn - * @param request - * @param userId - * @return - */ - - @GET - @Path("/{componentType}/{componentId}/filteredDataByParams") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = componentId.toLowerCase(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - log.trace("get component with id {} filtered by ui params", componentId); - Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); - - if (actionResponse.isRight()) { - log.debug("failed to get component data filtered by ui params"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - - @GET - @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getFilteredComponentInstanceProperties( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("propertyNameFragment") final String propertyNameFragment, - @QueryParam("resourceType") List<String> resourceTypes, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - User user = new User(); - user.setUserId(userId); - log.debug("User Id is {}" , userId); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class); - List<String> propertyNameFragments = new ArrayList<>(); - propertyNameFragments.add(propertyNameFragment); - filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); - if(CollectionUtils.isNotEmpty(resourceTypes)){ - filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); - } - Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties"); - log.debug("Getting of filtered component instance properties failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } + private static final Logger log = LoggerFactory.getLogger(ComponentServlet.class); + + @GET + @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + Response response; + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum != null) { + ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); + Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); + if (eitherConformanceLevel.isRight()) { + response = buildErrorResponse(eitherConformanceLevel.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); + } + } else { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return response; + } + + @GET + @Path("/{componentType}/{componentId}/requirmentsCapabilities") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + Response response; + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum != null) { + try { + ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); + Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); + if (eitherRequirementsAndCapabilities.isRight()) { + response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value())); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); + log.debug("getRequirementAndCapabilities failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } else { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return response; + } + + @GET + @Path("/{componentType}/latestversion/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); + + Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @POST + @Path("/{componentType}/latestversion/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + List<String> componentUids = data; + if (log.isDebugEnabled()) + log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); + + Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); + + if (actionResponse.isRight()) { + if (log.isDebugEnabled()) + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + return responseToReturn; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @GET + @Path("/{componentType}/latestversion/notabstract/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @GET + @Path("/{componentType}/{componentId}/componentInstances") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText); + if (actionResponse.isRight()) { + log.debug("failed to get all component instances filtered by properties and inputs", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType); + log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + + /** + * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. + * for example: list of the string "properties, inputs" will return component with the list of properties and inputs. + * + * @param componentType + * @param componentId + * @param dataParamsToReturn + * @param request + * @param userId + * @return + */ + + @GET + @Path("/{componentType}/{componentId}/filteredDataByParams") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response; + + try { + String resourceIdLower = componentId.toLowerCase(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + log.trace("get component with id {} filtered by ui params", componentId); + Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); + + if (actionResponse.isRight()) { + log.debug("failed to get component data filtered by ui params"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + + @GET + @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getFilteredComponentInstanceProperties( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("propertyNameFragment") final String propertyNameFragment, + @QueryParam("resourceType") List<String> resourceTypes, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + User user = new User(); + user.setUserId(userId); + log.debug("User Id is {}" , userId); + Response response; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class); + List<String> propertyNameFragments = new ArrayList<>(); + propertyNameFragments.add(propertyNameFragment); + filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); + if(CollectionUtils.isNotEmpty(resourceTypes)){ + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); + } + Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties"); + log.debug("Getting of filtered component instance properties failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java index 164b1d7665..f8aa39c478 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java @@ -20,18 +20,7 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - +import com.jcabi.aspects.Loggable; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.Constants; @@ -39,7 +28,11 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "/" path) @@ -48,78 +41,78 @@ import com.jcabi.aspects.Loggable; @Path("/configmgr") public class ConfigMgrServlet extends BasicServlet { - private static Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class); - @GET - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { - String result = null; + String result = null; - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); + ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - if (type == null || type.equals("configuration")) { + if (type == null || type.equals("configuration")) { - Configuration configuration = configurationManager.getConfiguration(); - if (configuration == null) { - log.warn("Configuration of type {} was not found", Configuration.class); - } else { - log.info("The value returned from getConfig is {}", configuration); + Configuration configuration = configurationManager.getConfiguration(); + if (configuration == null) { + log.warn("Configuration of type {} was not found", Configuration.class); + } else { + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } - } + } + } - return result; + return result; - } + } - @POST - @Path("/set1") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) { + @POST + @Path("/set1") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - return "ok"; + return "ok"; - } + } - @POST - @Path("/set2") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) { + @POST + @Path("/set2") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - } + } - @PUT - @Path("/setput1") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) { + @PUT + @Path("/setput1") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - return "ok"; + return "ok"; - } + } - @PUT - @Path("/setput2") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) { + @PUT + @Path("/setput2") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java index 79202ac94f..a56065fcdf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - +import com.jcabi.aspects.Loggable; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; @@ -35,7 +28,13 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "/" path) @@ -44,36 +43,36 @@ import com.jcabi.aspects.Loggable; @Path("/config") public class ConfigServlet extends BasicServlet { - private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class); - @GET - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public String getConfig(@Context final HttpServletRequest request) { + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public String getConfig(@Context final HttpServletRequest request) { - String result = null; + String result = null; - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR); - if (configurationSource != null) { - Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null); + ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR); + if (configurationSource != null) { + Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null); - if (configuration == null) { - log.warn("Configuration of type {} was not found", Configuration.class); - } - log.debug("{}", configuration); - log.info("Info level ENABLED..."); - log.info("The value returned from getConfig is {}", configuration); + if (configuration == null) { + log.warn("Configuration of type {} was not found", Configuration.class); + } + log.debug("{}", configuration); + log.info("Info level ENABLED..."); + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } else { - log.warn("Source Configuration object was not initialized in the context."); - } + } else { + log.warn("Source Configuration object was not initialized in the context."); + } - return result; + return result; - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java index 943ed59e87..fda31e5032 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java @@ -20,21 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,179 +38,173 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/consumers") @Api(value = "Consumer Servlet", description = "Consumer Servlet") @Singleton public class ConsumerServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ConsumerServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConsumerServlet.class); - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ONAP consumer credentials", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ECOMP consumer credentials", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); - Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - if (convertionResponse.isRight()) { - log.debug("failed to create Consumer"); - return buildErrorResponse(convertionResponse.right().value()); - } + if (convertionResponse.isRight()) { + log.debug("failed to create Consumer"); + return buildErrorResponse(convertionResponse.right().value()); + } - ConsumerDefinition consumer = convertionResponse.left().value(); + ConsumerDefinition consumer = convertionResponse.left().value(); - Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer); + Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer); - if (actionResult.isRight()) { - log.debug("failed to create Consumer"); - return buildErrorResponse(actionResult.right().value()); - } + if (actionResult.isRight()) { + log.debug("failed to create Consumer"); + return buildErrorResponse(actionResult.right().value()); + } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer"); - log.debug("create consumer failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @GET - @Path("/{consumerId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) - public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); - - Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get consumer"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); - log.debug("get consumer failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/{consumerId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) - public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); - - Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to delete consumer"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); - log.debug("delete consumer failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - private ConsumerBusinessLogic getConsumerBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class); - - return consumerBL; - } - - public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) { - ConsumerDefinition consumer = null; - Gson gson = new Gson(); - try { - log.trace("convert json to object. json=\n {}", data); - consumer = gson.fromJson(data, ConsumerDefinition.class); - if (consumer == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - return Either.left(consumer); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer"); + log.debug("create consumer failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @GET + @Path("/{consumerId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) + public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); + + Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get consumer"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); + log.debug("get consumer failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/{consumerId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) + public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); + + Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to delete consumer"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); + log.debug("delete consumer failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + private ConsumerBusinessLogic getConsumerBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class); + + return consumerBL; + } + + public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) { + ConsumerDefinition consumer = null; + Gson gson = new Gson(); + try { + log.trace("convert json to object. json=\n {}", data); + consumer = gson.fromJson(data, ConsumerDefinition.class); + if (consumer == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + //TODO call correct audit event method!!! - consumer!!! + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum); + return Either.right(responseFormat); + } + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + //TODO call correct audit event method!!! - consumer!!! + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum); + return Either.right(responseFormat); + } + return Either.left(consumer); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java index 4f8bffa066..faf02dc5ca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java @@ -20,12 +20,10 @@ package org.openecomp.sdc.be.servlets; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; - +import com.jcabi.aspects.Loggable; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -33,122 +31,78 @@ import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; -import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jcabi.aspects.Loggable; -//import org.openecomp.sdc.be.builders.tosca.api.TopologyService; -//import org.openecomp.sdc.be.tosca.parsers.ParserMode; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/services") public class CsarBuildServlet extends ToscaDaoServlet { - private static Logger log = LoggerFactory.getLogger(CsarBuildServlet.class.getName()); - - @GET - @Path("/{serviceName}/{serviceVersion}") - public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { - - return null;// buildToscaCsar(request, serviceName, serviceVersion); - - } - - @GET - @Path("/{serviceName}/{serviceVersion}/csar") - public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { - - return null; // buildToscaCsar(request, serviceName, serviceVersion); - - } - - /* - * private Response buildToscaCsar(final HttpServletRequest request, String serviceName, String serviceVersion) { log.debug("Building CSAR for service:{} , version:{}", serviceName, serviceVersion); ServletContext context = - * request.getSession().getServletContext(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); String fileName = - * serviceName+"_"+serviceVersion+".zip"; - * - * IResourceUploader resourceUploader = getResourceUploader(context); TopologyService topologyService = getToscaYamlBuilder(context).getServiceYaml(serviceName, serviceVersion, ParserMode.CSAR, "Scripts"); try { - * - * - * //Add Service yml to Zip addZipEntry(zipOutputStream, "Definitions/"+serviceName+".yaml", topologyService.getTopologyServiceYaml()); - * - * //Add Resources to Zip addResourcesToZip(zipOutputStream, topologyService); - * - * //Add Artifacts to Zip addArtifactsToZip(serviceName, serviceVersion, zipOutputStream, resourceUploader); - * - * //Prepare Tosca metadata addToscaMetaToZip(zipOutputStream, topologyService, resourceUploader); - * - * } - * - * catch (IOException e) { log.error("Failed to create CSAR file", e); return null; } finally{ try { byteArrayOutputStream.close(); zipOutputStream.close(); } catch (IOException e) { log.error("Failed to close output srream", e); } - * - * } return buildResponse(fileName, byteArrayOutputStream); - * - * - * } - */ - - public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; - - protected String[] prepareToscaMetaHeader(String serviceName) { - return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n", - "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" }; - } - - protected String getAppliactionMime(String fileName) { - String mimeType; - if (fileName.contains(".sh")) { - mimeType = "x-sh"; - } else if (fileName.contains(".yang")) { - mimeType = "yang"; - } - - else if (fileName.contains(".rar")) { - mimeType = "x-rar-compressed"; - } - - else if (fileName.contains(".zip")) { - mimeType = "zip"; - } - - else if (fileName.contains(".tar")) { - mimeType = "x-tar"; - } - - else if (fileName.contains(".7z")) { - mimeType = "x-7z-compressed"; - } - - else { - // Undefined - mimeType = "undefined"; - } - return mimeType; - } - - protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) { - // return "Scripts/"+nodeTamplateName+"/"+ - // artifactData.getArtifactName(); - return "Scripts/" + nodeTamplateName + "/" + artifactData.getId(); - } - - protected String getResourcePath(String resourceName) { - return "Definitions/" + resourceName + ".yaml"; - } - - private byte[] encodeString(String data) throws CharacterCodingException { - Charset charset = Charset.forName("UTF-8"); - CharsetEncoder encoder = charset.newEncoder(); - ByteBuffer bb = encoder.encode(CharBuffer.wrap(data.toCharArray())); - byte[] ba = new byte[bb.limit()]; - bb.get(ba); - return ba; - } - - @Override - public Logger getLogger() { - return log; - } + private static final Logger log = LoggerFactory.getLogger(CsarBuildServlet.class); + + @GET + @Path("/{serviceName}/{serviceVersion}") + public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { + + return null;// buildToscaCsar(request, serviceName, serviceVersion); + + } + + @GET + @Path("/{serviceName}/{serviceVersion}/csar") + public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { + + return null; // buildToscaCsar(request, serviceName, serviceVersion); + + } + + + public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; + + protected String[] prepareToscaMetaHeader(String serviceName) { + return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n", + "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" }; + } + + protected String getAppliactionMime(String fileName) { + String mimeType; + if (fileName.contains(".sh")) { + mimeType = "x-sh"; + } else if (fileName.contains(".yang")) { + mimeType = "yang"; + } + + else if (fileName.contains(".rar")) { + mimeType = "x-rar-compressed"; + } + + else if (fileName.contains(".zip")) { + mimeType = "zip"; + } + + else if (fileName.contains(".tar")) { + mimeType = "x-tar"; + } + + else if (fileName.contains(".7z")) { + mimeType = "x-7z-compressed"; + } + + else { + // Undefined + mimeType = "undefined"; + } + return mimeType; + } + + protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) { + return "Scripts/" + nodeTamplateName + "/" + artifactData.getId(); + } + + protected String getResourcePath(String resourceName) { + return "Definitions/" + resourceName + ".yaml"; + } + + @Override + public Logger getLogger() { + return log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java new file mode 100644 index 0000000000..40de94bd6a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.servlets; + +import org.eclipse.jetty.http.HttpStatus; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class DefaultExceptionMapper implements ExceptionMapper<Exception> { + + @Override + public Response toResponse(Exception exception) { + return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500) + .entity(exception.getMessage()) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java index 4215560020..dca41210cc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java @@ -20,20 +20,12 @@ package org.openecomp.sdc.be.servlets; -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -47,14 +39,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * Root resource (exposed at "/" path) */ @@ -63,107 +55,105 @@ import io.swagger.annotations.ApiResponses; @Api(value = "Distribution Service Servlet", description = "Distribution Service Servlet") @Singleton public class DistributionServiceServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class.getName()); - - @Resource - private DistributionMonitoringBusinessLogic distributionMonitoringLogic; - - @GET - @Path("/services/{serviceUUID}/distribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - try { - Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId); - - if (actionResponse.isRight()) { - - responseFormat = actionResponse.right().value(); - response = buildErrorResponse(responseFormat); - } else { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution list for Service"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service"); - log.debug("failed to get service distribution statuses", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - - response = buildErrorResponse(responseFormat); - return response; - } - - } - - @GET - @Path("/services/distribution/{did}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") }) - public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - try { - Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId); - - if (actionResponse.isRight()) { - - responseFormat = actionResponse.right().value(); - log.debug("failed to fount statuses for did {} {}", did, responseFormat); - response = buildErrorResponse(responseFormat); - } else { - - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value()); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution Status"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status"); - log.debug("failed to get distribution status ", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - - response = buildErrorResponse(responseFormat); - return response; - } - - } - - private void init(HttpServletRequest request) { - if (distributionMonitoringLogic == null) { - distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext()); - } - } - - private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class); - return distributionBl; - } + private static final Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class); + + @Resource + private DistributionMonitoringBusinessLogic distributionMonitoringLogic; + + @GET + @Path("/services/{serviceUUID}/distribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + try { + Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId); + + if (actionResponse.isRight()) { + + responseFormat = actionResponse.right().value(); + response = buildErrorResponse(responseFormat); + } else { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service"); + log.debug("failed to get service distribution statuses", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + + response = buildErrorResponse(responseFormat); + return response; + } + + } + + @GET + @Path("/services/distribution/{did}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") }) + public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + try { + Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId); + + if (actionResponse.isRight()) { + + responseFormat = actionResponse.right().value(); + log.debug("failed to fount statuses for did {} {}", did, responseFormat); + response = buildErrorResponse(responseFormat); + } else { + + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value()); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status"); + log.debug("failed to get distribution status ", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + + response = buildErrorResponse(responseFormat); + return response; + } + + } + + private void init(HttpServletRequest request) { + if (distributionMonitoringLogic == null) { + distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext()); + } + } + + private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class); + return distributionBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java index 7a42360355..1a6fb20b46 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java @@ -20,29 +20,11 @@ package org.openecomp.sdc.be.servlets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; +import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,12 +32,9 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.info.ArtifactTypesInfo; -import org.openecomp.sdc.be.model.ArtifactType; -import org.openecomp.sdc.be.model.Category; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.Tag; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -67,14 +46,17 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Path("/v1/") @@ -89,554 +71,536 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ElementServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ElementServlet.class.getName()); - - /* - ****************************************************************************** - * NEW CATEGORIES category / \ subcategory subcategory / grouping - ******************************************************************************/ - - /* - * - * - * CATEGORIES - */ - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all component categories - @GET - @Path("/categories/{componentType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"), - @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId); - if (either.isRight()) { - log.debug("No categories were found for type {}", componentType); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories"); - log.debug("getComponentCategories failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/categories") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<UiCategories, ResponseFormat> either = elementBL.getAllCategories(userId); - if (either.isRight()) { - log.debug("No categories were found"); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories"); - log.debug("getAllCategories failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @POST - @Path("/category/{componentType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentCategory( - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class); - - Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId); - if (createResourceCategory.isRight()) { - return buildErrorResponse(createResourceCategory.right().value()); - } - - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createResourceCategory.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); - log.debug("createResourceCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId); - - if (createResourceCategory.isRight()) { - return buildErrorResponse(createResourceCategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); - log.debug("createResourceCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - /* - * - * - * SUBCATEGORIES - * - */ - - @POST - @Path("/category/{componentType}/{categoryId}/subCategory") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentSubCategory( - @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class); - - Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId); - if (createSubcategory.isRight()) { - return buildErrorResponse(createSubcategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createSubcategory.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create sub-category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category"); - log.debug("createComponentSubCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId, - @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId); - if (deleteSubResourceCategory.isRight()) { - return buildErrorResponse(deleteSubResourceCategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category"); - log.debug("deleteComponentSubCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - /* - * GROUPINGS - */ - @POST - @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"), - @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, - @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class); - - Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId); - if (createGrouping.isRight()) { - return buildErrorResponse(createGrouping.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createGrouping.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create grouping"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping"); - log.debug("createComponentGrouping failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId, - @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId); - if (deleteGrouping.isRight()) { - return buildErrorResponse(deleteGrouping.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component grouping"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping"); - log.debug("deleteGrouping failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all tags - @GET - @Path("/tags") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getTags) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No tags were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Tags"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags"); - log.debug("getAllTags failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all property scopes - @GET - @Path("/propertyScopes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getPropertyScopes) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No property scopes were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property Scopes Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories"); - log.debug("getPropertyScopes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all artifact types - @GET - @Path("/artifactTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET - getArtifactTypes) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - - Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - ArtifactTypesInfo typesResponse = new ArtifactTypesInfo(); - typesResponse.setArtifactTypes(either.left().value()); - typesResponse.setHeatDefaultTimeout(defaultHeatTimeout); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); - log.debug("getArtifactTypes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all artifact types - @GET - @Path("/configuration/ui") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getConfiguration) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either<List<ArtifactType>, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId); - Either<Integer, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout(); - Either<Map<String, Object>, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes(); - Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap(); - - if (otherEither.isRight() || otherEither.left().value() == null) { - log.debug("No other artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) { - log.debug("No deployment artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) { - log.debug("heat default timeout was not found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) { - log.debug("No resource types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - Map<String, Object> artifacts = new HashMap<String, Object>(); - Map<String, Object> configuration = new HashMap<String, Object>(); - - artifacts.put("other", otherEither.left().value()); - artifacts.put("deployment", deploymentEither.left().value()); - configuration.put("artifacts", artifacts); - configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value()); - configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames()); - configuration.put("roles", elementBL.getAllSupportedRoles()); - configuration.put("resourceTypes", resourceTypesMap.left().value()); - configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); - log.debug("getArtifactTypes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all followed resources and services - @GET - @Path("/followed") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Response res = null; - User userData = null; - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - // Getting the user - Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); - if (either.isRight()) { - // Couldn't find or otherwise fetch the user - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } - - if (either.left().value() != null) { - userData = either.left().value(); - Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData); - // res = - // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - // followedResourcesServices.left().value()); - if (followedResourcesServices.isRight()) { - log.debug("failed to get followed resources services "); - return buildErrorResponse(followedResourcesServices.right().value()); - } - Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value()); - res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); - } else { - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Followed Resources / Services Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories"); - log.debug("Getting followed resources/services failed with exception", e); - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return res; - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all certified resources and services and their last version - @GET - @Path("/screen") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) { - - Response res = null; - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes); - - if (catalogData.isRight()) { - log.debug("failed to get catalog data"); - return buildErrorResponse(catalogData.right().value()); - } - Object data = RepresentationUtils.toRepresentation(catalogData.left().value()); - res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Catalog Components"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components"); - log.debug("Getting catalog components failed with exception", e); - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return res; - } - - @DELETE - @Path("/inactiveComponents/{componentType}") - public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType); - if (nodeType == null) { - log.info("componentType is not valid: {]", componentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - List<NodeTypeEnum> componentsList = new ArrayList<NodeTypeEnum>(); - componentsList.add(nodeType); - try { - ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context); - Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList); - Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType); - - if (cleanResult.isRight()) { - log.debug("failed to delete marked components of type {}", nodeType); - response = buildErrorResponse(cleanResult.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Marked Components"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components"); - log.debug("delete marked components failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/ecompPortalMenu") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve ONAP portal menu - MOC", httpMethod = "GET", notes = "Retrieve ONAP portal menu", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ONAP portal menu") }) - public Response getListOfCsars(@Context final HttpServletRequest request) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]"); - } + private static final Logger log = LoggerFactory.getLogger(ElementServlet.class); + + /* + ****************************************************************************** + * NEW CATEGORIES category / \ subcategory subcategory / grouping + ******************************************************************************/ + + /* + * + * + * CATEGORIES + */ + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all component categories + @GET + @Path("/categories/{componentType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"), + @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId); + if (either.isRight()) { + log.debug("No categories were found for type {}", componentType); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories"); + log.debug("getComponentCategories failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/categories") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<UiCategories, ResponseFormat> either = elementBL.getAllCategories(userId); + if (either.isRight()) { + log.debug("No categories were found"); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories"); + log.debug("getAllCategories failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @POST + @Path("/category/{componentType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentCategory( + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class); + + Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId); + if (createResourceCategory.isRight()) { + return buildErrorResponse(createResourceCategory.right().value()); + } + + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createResourceCategory.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); + log.debug("createResourceCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId); + + if (createResourceCategory.isRight()) { + return buildErrorResponse(createResourceCategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); + log.debug("createResourceCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + /* + * + * + * SUBCATEGORIES + * + */ + + @POST + @Path("/category/{componentType}/{categoryId}/subCategory") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentSubCategory( + @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class); + + Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId); + if (createSubcategory.isRight()) { + return buildErrorResponse(createSubcategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createSubcategory.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category"); + log.debug("createComponentSubCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId, + @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId); + if (deleteSubResourceCategory.isRight()) { + return buildErrorResponse(deleteSubResourceCategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category"); + log.debug("deleteComponentSubCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + /* + * GROUPINGS + */ + @POST + @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"), + @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, + @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class); + + Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId); + if (createGrouping.isRight()) { + return buildErrorResponse(createGrouping.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createGrouping.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping"); + log.debug("createComponentGrouping failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId, + @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId); + if (deleteGrouping.isRight()) { + return buildErrorResponse(deleteGrouping.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping"); + log.debug("deleteGrouping failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all tags + @GET + @Path("/tags") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getTags) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No tags were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags"); + log.debug("getAllTags failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all property scopes + @GET + @Path("/propertyScopes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getPropertyScopes) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No property scopes were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories"); + log.debug("getPropertyScopes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all artifact types + @GET + @Path("/artifactTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET - getArtifactTypes) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + + Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + ArtifactTypesInfo typesResponse = new ArtifactTypesInfo(); + typesResponse.setArtifactTypes(either.left().value()); + typesResponse.setHeatDefaultTimeout(defaultHeatTimeout); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); + log.debug("getArtifactTypes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all artifact types + @GET + @Path("/configuration/ui") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getConfiguration) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either<List<ArtifactType>, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId); + Either<Integer, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout(); + Either<Map<String, Object>, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes(); + Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap(); + + if (otherEither.isRight() || otherEither.left().value() == null) { + log.debug("No other artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) { + log.debug("No deployment artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) { + log.debug("heat default timeout was not found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) { + log.debug("No resource types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + Map<String, Object> artifacts = new HashMap<String, Object>(); + Map<String, Object> configuration = new HashMap<String, Object>(); + + artifacts.put("other", otherEither.left().value()); + artifacts.put("deployment", deploymentEither.left().value()); + configuration.put("artifacts", artifacts); + configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value()); + configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames()); + configuration.put("roles", elementBL.getAllSupportedRoles()); + configuration.put("resourceTypes", resourceTypesMap.left().value()); + configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); + log.debug("getArtifactTypes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all followed resources and services + @GET + @Path("/followed") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Response res = null; + User userData = null; + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + // Getting the user + Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); + if (either.isRight()) { + // Couldn't find or otherwise fetch the user + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } + + if (either.left().value() != null) { + userData = either.left().value(); + Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData); + if (followedResourcesServices.isRight()) { + log.debug("failed to get followed resources services "); + return buildErrorResponse(followedResourcesServices.right().value()); + } + Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value()); + res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); + } else { + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories"); + log.debug("Getting followed resources/services failed with exception", e); + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return res; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all certified resources and services and their last version + @GET + @Path("/screen") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) { + + Response res = null; + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId); + + if (catalogData.isRight()) { + log.debug("failed to get catalog data"); + return buildErrorResponse(catalogData.right().value()); + } + Object data = RepresentationUtils.toRepresentation(catalogData.left().value()); + res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components"); + log.debug("Getting catalog components failed with exception", e); + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return res; + } + + @DELETE + @Path("/inactiveComponents/{componentType}") + public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType); + if (nodeType == null) { + log.info("componentType is not valid: {]", componentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + List<NodeTypeEnum> componentsList = new ArrayList<NodeTypeEnum>(); + componentsList.add(nodeType); + try { + ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context); + Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList); + Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType); + + if (cleanResult.isRight()) { + log.debug("failed to delete marked components of type {}", nodeType); + response = buildErrorResponse(cleanResult.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components"); + log.debug("delete marked components failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/ecompPortalMenu") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve ecomp portal menu - MOC", httpMethod = "GET", notes = "Retrieve ecomp portal menu", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ecomp portal menu") }) + public Response getListOfCsars(@Context final HttpServletRequest request) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java index 22391bbdc1..100fd36e27 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java @@ -20,22 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.common.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,199 +42,217 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; /** * Root resource (exposed at "/" path) */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) @Path("/v1/catalog") -@Api(value = "Resource Group Servlet", description = "Resource Group Servlet") +@Api(value = "Resource Group Servlet") @Singleton public class GroupServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(GroupServlet.class.getName()); - - private Gson gson = new Gson(); - - @GET - @Path("/{containerComponentType}/{componentId}/groups/{groupId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Group not found") }) - public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - try { - - GroupBusinessLogic businessLogic = this.getGroupBL(context); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic - .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", containerComponentType); - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @PUT - @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupMetadata( - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @ApiParam(value = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User user = new User(); - user.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - GroupBusinessLogic businessLogic = getGroupBL(context); - - Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class); - if (convertResponse.isRight()) { - log.debug("failed to parse group"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - GroupDefinition updatedGroup = convertResponse.left().value(); - - // Update GroupDefinition - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic - .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true); - - if (actionResponse.isRight()) { - log.debug("failed to update GroupDefinition"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - GroupDefinition group = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(group); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata"); - log.debug("update group metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /** - * Updates List of properties on a group (only values) - * @param containerComponentType - * @param componentId - * @param groupUniqueId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @ApiParam(value = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(log); - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User user = new User(); - user.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - GroupBusinessLogic businessLogic = getGroupBL(context); - Either<List<GroupProperty>, ResponseFormat> convertResponse = parseListOfObjects(data, - new TypeToken<List<GroupProperty>>() { - }.getType()); - - if (convertResponse.isRight()) { - log.debug("failed to parse group Property"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - List<GroupProperty> groupPropertyToUpdate = convertResponse.left().value(); - - // Update GroupDefinition - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either<List<GroupProperty>, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties( - componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false); - - if (actionResponse.isRight()) { - log.debug("failed to update GroupDefinition"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - List<GroupProperty> groupProperty = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(groupProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties"); - log.debug("update group properties failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } + private static final Logger log = LoggerFactory.getLogger(GroupServlet.class); + public static final String START_HANDLE_REQUEST = "Start handle request of {}"; + + @POST + @Path("/{containerComponentType}/{componentId}/groups/{groupType}") + @ApiOperation(value = "Create group ", httpMethod = "POST", notes = "Creates new group in component and returns it", response = GroupDefinition.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Group created"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Component not found"), + @ApiResponse(code = 500, message = "Internal Error") + }) + public Response createGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupType") final String type, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(post) Start handle request of {}", url); + + GroupBusinessLogic businessLogic = getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition groupDefinition = businessLogic + .createGroup(type, componentTypeEnum, componentId, userId); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), + groupDefinition); + } + + @GET + @Path("/{containerComponentType}/{componentId}/groups/{groupId}") + @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "group found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Group not found")}) + public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + try { + + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic + .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", containerComponentType); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}") + @ApiOperation(value = "Delete Group", httpMethod = "DELETE", notes = "Returns deleted group id", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "ResourceInstance deleted"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Component not found"), + @ApiResponse(code = 500, message = "Internal Error") + }) + public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupUniqueId") final String groupId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(START_HANDLE_REQUEST, url); + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition groupDefinition = businessLogic + .deleteGroup(componentTypeEnum, componentId, groupId, userId); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId()); + } + + @PUT + @Path("/{containerComponentType}/{componentId}/groups/{groupId}") + @ApiOperation(value = "Update Group metadata", httpMethod = "PUT", notes = "Returns updated Group", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Group updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / group Not found")}) + public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupId") final String groupId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "GroupDefinition", required = true) GroupDefinition groupData, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition updatedGroup = businessLogic.updateGroup(componentTypeEnum, componentId, groupId, userId, groupData); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup); + } + + /** + * Updates List of properties on a group (only values) + * @param containerComponentType + * @param componentId + * @param groupUniqueId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") + @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @ApiParam(value = "Group Properties to be Updated", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(log); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(START_HANDLE_REQUEST, url); + + User user = new User(); + user.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + GroupBusinessLogic businessLogic = getGroupBL(context); + Either<List<GroupProperty>, ResponseFormat> convertResponse = parseListOfObjects(data, + new TypeToken<List<GroupProperty>>() { + }.getType()); + + if (convertResponse.isRight()) { + log.debug("failed to parse group Property"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + List<GroupProperty> groupPropertyToUpdate = convertResponse.left().value(); + + // Update GroupDefinition + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either<List<GroupProperty>, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties( + componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false); + + if (actionResponse.isRight()) { + log.debug("failed to update GroupDefinition"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + List<GroupProperty> groupProperty = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(groupProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties"); + log.debug("update group properties failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java new file mode 100644 index 0000000000..a056b1d454 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; +import org.openecomp.sdc.be.mixin.GroupTypeMixin; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.view.ResponseView; +import org.openecomp.sdc.common.api.Constants; +import org.springframework.stereotype.Controller; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "group types resource") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class GroupTypesEndpoint { + + private final GroupTypeBusinessLogic groupTypeBusinessLogic; + + public GroupTypesEndpoint(GroupTypeBusinessLogic groupTypeBusinessLogic) { + this.groupTypeBusinessLogic = groupTypeBusinessLogic; + } + + @GET + @Path("/groupTypes") + @ApiOperation(value = "Get group types ", httpMethod = "GET", notes = "Returns group types", response = GroupTypeDefinition.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "group types found"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 500, message = "Internal Error") + }) + @ResponseView(mixin = {GroupTypeMixin.class}) + public List<GroupTypeDefinition> getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed") + @QueryParam("internalComponentType") String internalComponentType) { + return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java index 4de5488351..1d627e6fd3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java @@ -20,25 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.InputsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -58,398 +47,309 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) -@Path("/v1/catalog") @Api(value = "Input Catalog", description = "Input Servlet") +@Path("/v1/catalog") @Singleton +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) public class InputsServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName()); - - @GET - @Path("/services/{componentId}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @QueryParam("fromId") String fromName, - @QueryParam("amount") int amount, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - - InputsBusinessLogic businessLogic = getInputBL(context); - - Either<List<InputDefinition>, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, componentId, fromName, amount); - if (inputsResponse.isRight()) { - log.debug("failed to get inputs {}", componentType); - return buildErrorResponse(inputsResponse.right().value()); - } - Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); - log.debug("getInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - @POST - @Path("/{containerComponentType}/{componentId}/update/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInputs( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, - @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) { - - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - try { - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either<InputDefinition, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);; - if(inputEither.isRight()){ - log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - InputDefinition input = inputEither.left().value(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", input); - - ServletContext context = request.getSession().getServletContext(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); - - InputsBusinessLogic businessLogic = getInputBL(context); - if (businessLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); - } - - Either<InputDefinition, ResponseFormat> actionResponse = businessLogic.updateInputValue(componentType, componentId, input, userId, true, false); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - InputDefinition resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @GET - @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, - @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId); - if (inputsResponse.isRight()) { - log.debug("failed to get component instance inputs {}", componentType); - return buildErrorResponse(inputsResponse.right().value()); - } - Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); - log.debug("getInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, - @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); - if (inputPropertiesRes.isRight()) { - log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId); - return buildErrorResponse(inputPropertiesRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get properties by input id {}, for component instance {} ", inputId, instanceId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId); - log.debug("getInputPropertiesForComponentInstance failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId); - - if (inputsRes.isRight()) { - log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); - return buildErrorResponse(inputsRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); - log.debug("getInputsForComponentInput failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/inputs/{inputId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); - - if (inputsRes.isRight()) { - log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); - return buildErrorResponse(inputsRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); - log.debug("getInputsForComponentInput failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - public Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - - @POST - @Path("/{componentType}/{componentId}/create/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier); - if (componentInstInputsMapRes.isRight()) { - log.debug("failed to parse componentInstInputsMap"); - response = buildErrorResponse(componentInstInputsMapRes.right().value()); - return response; - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value(); - - Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); - if (inputPropertiesRes.isRight()) { - log.debug("failed to create inputs for service: {}", componentId); - return buildErrorResponse(inputPropertiesRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create inputs for service with id: {}", componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); - log.debug("createMultipleInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - - @DELETE - @Path("/{componentType}/{componentId}/delete/{inputId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) - public Response deleteInput ( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("inputId") final String inputId, + private static final Logger log = LoggerFactory.getLogger(InputsServlet.class); + + @POST + @Path("/{containerComponentType}/{componentId}/update/inputs") + @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInputs( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + try { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE); + if(inputsEither.isRight()){ + log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value()); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value()); + + log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate); + + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); + + InputsBusinessLogic businessLogic = getInputBL(context); + if (businessLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); + } + + Either<List<InputDefinition>, ResponseFormat> actionResponse = businessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + List<InputDefinition> componentInputs = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(componentInputs); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } + catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @GET + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") + @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, + @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId); + if (inputsResponse.isRight()) { + log.debug("failed to get component instance inputs {}", componentType); + return buildErrorResponse(inputsResponse.right().value()); + } + Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); + log.debug("getInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties") + @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, + @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); + if (inputPropertiesRes.isRight()) { + log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId); + return buildErrorResponse(inputPropertiesRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId); + log.debug("getInputPropertiesForComponentInstance failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs") + @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId); + + if (inputsRes.isRight()) { + log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); + return buildErrorResponse(inputsRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); + log.debug("getInputsForComponentInput failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/inputs/{inputId}") + @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); + + if (inputsRes.isRight()) { + log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); + return buildErrorResponse(inputsRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); + log.debug("getInputsForComponentInput failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + } + + @POST + @Path("/{componentType}/{componentId}/create/inputs") + @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier); + if (componentInstInputsMapRes.isRight()) { + log.debug("failed to parse componentInstInputsMap"); + response = buildErrorResponse(componentInstInputsMapRes.right().value()); + return response; + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value(); + + Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); + if (inputPropertiesRes.isRight()) { + log.debug("failed to create inputs for service: {}", componentId); + return buildErrorResponse(inputPropertiesRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); + log.debug("createMultipleInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + + @DELETE + @Path("/{componentType}/{componentId}/delete/{inputId}/input") + @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) + public Response deleteInput ( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); - if (deleteInput.isRight()){ - ResponseFormat deleteResponseFormat = deleteInput.right().value(); - response = buildErrorResponse(deleteResponseFormat); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); - } catch (Exception e){ - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); - log.debug("Delete input failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - - /*@PUT - @Path("/{componentType}/{componentId}/edit/{inputId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) - public Response editInputValue ( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("inputId") final String inputId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); - if (deleteInput.isRight()){ - ResponseFormat deleteResponseFormat = deleteInput.right().value(); - response = buildErrorResponse(deleteResponseFormat); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); - } catch (Exception e){ - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); - log.debug("Delete input failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - }*/ - - protected InputsBusinessLogic getInputBL(ServletContext context) { - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - InputsBusinessLogic inputsBusinessLogic = webApplicationContext.getBean(InputsBusinessLogic.class); - return inputsBusinessLogic; - } + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentId, userId, inputId); + if (deleteInput.isRight()){ + ResponseFormat deleteResponseFormat = deleteInput.right().value(); + response = buildErrorResponse(deleteResponseFormat); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); + } catch (Exception e){ + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); + log.debug("Delete input failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private InputsBusinessLogic getInputBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(InputsBusinessLogic.class); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java index c2d7c2a6a1..5720c56c38 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java @@ -20,20 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.codehaus.jackson.map.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; @@ -52,145 +42,115 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet") @Singleton public class LifecycleServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(LifecycleServlet.class.getName()); - - @POST - @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") }) - public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo, - @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection, - @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - LifecycleBusinessLogic businessLogic = getLifecycleBL(context); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Response response = null; - - // get modifier from graph - log.debug("get modifier properties"); - Either<User, ResponseFormat> eitherGetUser = getUser(request, userId); - if (eitherGetUser.isRight()) { - return buildErrorResponse(eitherGetUser.right().value()); - } - User user = eitherGetUser.left().value(); - - String resourceIdLower = componentId.toLowerCase(); - log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower); - Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user); - if (validateEnum.isRight()) { - return validateEnum.right().value(); - } - - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); - - try { - if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { - // Either<LifecycleChangeInfo, ResponseFormat > changeInfoResult - // = - // getComponentsUtils().convertJsonToObjectUsingObjectMapper(jsonChangeInfo, - // user, LifecycleChangeInfo.class, - // AuditingActionEnum.CHECKOUT_RESOURCE, null); - ObjectMapper mapper = new ObjectMapper(); - changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); - } - } - - catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", jsonChangeInfo, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return buildErrorResponse(responseFormat); - } - - try { - LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); - if (componentType != null) { - Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); - - if (actionResponse.isRight()) { - log.info("failed to change resource state"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - log.debug("change state successful !!!"); - UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); - Object value = RepresentationUtils.toRepresentation(componentMetatdata); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); - return response; - } else { - log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return buildErrorResponse(error); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); - log.debug("change lifecycle state failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) { - LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; - try { - transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); - } catch (IllegalArgumentException e) { - log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(buildErrorResponse(error)); - } - return Either.left(transitionEnum); - } - -// private LifecycleBusinessLogic getLifecycleBL(ServletContext context) { -// WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); -// WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); -// LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class); -// return resourceBl; -// } -// -// protected Either<User, Response> getUser(final HttpServletRequest request, String userId) { -// -// Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); -// if (eitherCreator.isRight()) { -// log.info("createResource method - user is not listed. userId= {}", userId); -// ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); -// User user = new User("", "", userId, "", null, null); -// -// getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); -// return Either.right(buildErrorResponse(errorResponse)); -// } -// return Either.left(eitherCreator.left().value()); -// -// } + private static final Logger log = LoggerFactory.getLogger(LifecycleServlet.class); + + @POST + @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") }) + public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo, + @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection, + @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + LifecycleBusinessLogic businessLogic = getLifecycleBL(context); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Response response = null; + + // get modifier from graph + log.debug("get modifier properties"); + Either<User, ResponseFormat> eitherGetUser = getUser(request, userId); + if (eitherGetUser.isRight()) { + return buildErrorResponse(eitherGetUser.right().value()); + } + User user = eitherGetUser.left().value(); + + String resourceIdLower = componentId.toLowerCase(); + log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower); + Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user); + if (validateEnum.isRight()) { + return validateEnum.right().value(); + } + + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); + + try { + if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); + } + } + + catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", jsonChangeInfo, e); + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return buildErrorResponse(responseFormat); + } + + try { + LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); + if (componentType != null) { + Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); + + if (actionResponse.isRight()) { + log.info("failed to change resource state"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + log.debug("change state successful !!!"); + UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); + Object value = RepresentationUtils.toRepresentation(componentMetatdata); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); + return response; + } else { + log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return buildErrorResponse(error); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); + log.debug("change lifecycle state failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) { + LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; + try { + transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); + } catch (IllegalArgumentException e) { + log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(buildErrorResponse(error)); + } + return Either.left(transitionEnum); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java new file mode 100644 index 0000000000..b6e15cef9a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java @@ -0,0 +1,307 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + + +import org.openecomp.sdc.be.model.PolicyTargetDTO; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Provides REST API to create, retrieve, update, delete a policy + */ +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "Policy Servlet") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PolicyServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(PolicyServlet.class); + private final PolicyBusinessLogic policyBusinessLogic; + + public PolicyServlet(PolicyBusinessLogic policyBusinessLogic, ServletUtils servletUtils, ResourceImportManager resourceImportManager, ComponentsUtils componentsUtils) { + this.policyBusinessLogic = policyBusinessLogic; + this.servletUtils = servletUtils; + this.resourceImportManager = resourceImportManager; + this.componentsUtils = componentsUtils; + } + + @POST + @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}") + @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Policy already exist"), @ApiResponse(code = 404, message = "Component not found")}) + public Response createPolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyTypeName") final String policyTypeName, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true) + .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l), + this::buildErrorResponse)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy"); + log.error("Failed to create policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response updatePolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) { + init(log); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper); + if (policyWrapper.isEmpty()) { + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } + if (!policyWrapper.isEmpty()) { + policyWrapper.getInnerElement().setUniqueId(policyId); + responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true) + .either(this::buildOkResponse, + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy"); + log.error("Failed to update policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @GET + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response getPolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId) + .either(this::buildOkResponse, + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy"); + log.error("Failed to retrieve policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response deletePolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true) + .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null), + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy"); + log.error("Failed to delete policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @GET + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") + @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Properties found"),@ApiResponse(code = 400, message = "invalid content - Error: containerComponentType is invalid"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Componentorpolicy not found"), + @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.") })public Response getPolicyProperties(@ApiParam(value = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId, + @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + init(log); + try { + return convertToComponentType(containerComponentType) + .left() + .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId)) + .either(this::buildOkResponse, + this::buildErrorResponse); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties"); + log.debug("#getPolicyProperties - get Policy properties has failed.", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") + @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) { + init(log); + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper); + if (propertiesWrapper.isEmpty()) { + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } + if (!propertiesWrapper.isEmpty()) { + responseWrapper.setInnerElement( + policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true) + .either(this::buildOkResponse, this::buildErrorResponse)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy"); + log.error("Failed to update policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) { + Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>(); + if (StringUtils.isEmpty(userId)) { + log.error("Missing userId HTTP header. "); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID))); + } + if (responseWrapper.isEmpty()) { + validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType); + } + return componentTypeWrapper; + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update policy targets", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")}) + public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request, + List<PolicyTargetDTO> requestJson) { + try { + + Map<PolicyTargetType, List<String>> policyTarget = convertTargetDTOToBLTarget(requestJson); + if(policyTarget == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, StringUtils.join(requestJson.stream().map(PolicyTargetDTO::getType).collect(Collectors.toList())), ",")); + } + + return convertToComponentType(containerComponentType) + .left() + .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId)) + .either(this::buildOkResponse, + this::buildErrorResponse); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy"); + log.debug("Policy creation has been failed with the exception{}. ", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + private Map<PolicyTargetType, List<String>> convertTargetDTOToBLTarget(List<PolicyTargetDTO> targetDTOList) { + Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>(); + for (PolicyTargetDTO currentTarget : targetDTOList) { + if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){ + return null; + } + } + return policyTarget; + } + public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) { + PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type); + if(targetTypeEnum != null){ + policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds)); + return true; + } + else{ + return false; + } + } + + private List<String> validateUniquenessOfIds(List<String> uniqueIds) { + return uniqueIds.stream().distinct().collect(Collectors.toList()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java new file mode 100644 index 0000000000..aa4bfa87c7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.mixin.PolicyTypeMixin; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.view.ResponseView; +import org.openecomp.sdc.common.api.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "policy types resource") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PolicyTypesEndpoint extends BeGenericServlet{ + + private static final Logger log = LoggerFactory.getLogger(PolicyTypesEndpoint.class); + + private final PolicyTypeBusinessLogic policyTypeBusinessLogic; + + public PolicyTypesEndpoint(PolicyTypeBusinessLogic policyTypeBusinessLogic) { + this.policyTypeBusinessLogic = policyTypeBusinessLogic; + } + + @GET + @Path("/policyTypes") + @ApiOperation(value = "Get policy types ", httpMethod = "GET", notes = "Returns policy types", response = PolicyTypeDefinition.class, responseContainer="List") + @ApiResponses(value = { @ApiResponse(code = 200, message = "policy types found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.")}) + @ResponseView(mixin = {PolicyTypeMixin.class}) + public Response getPolicyTypes(@ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed") + @QueryParam("internalComponentType") String internalComponentType, + @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + log.debug("(get) Start handle request of GET policyTypes"); + try { + return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType) + .either(this::buildOkResponse, + this::buildErrorResponse); + } catch (Exception e) { + log.error("#getPolicyTypes - Exception occurred during get policy types", e); + return buildGeneralErrorResponse(); + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java index c0c987b78a..05ece30535 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java @@ -20,24 +20,9 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,262 +34,256 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Product Catalog", description = "Product Servlet") @Singleton public class ProductServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName()); - - @POST - @Path("/products") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"), - @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") }) - public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - Product product = RepresentationUtils.fromRepresentation(data, Product.class); - Either<Product, ResponseFormat> actionResponse = businessLogic.createProduct(product, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to create product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Product"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product"); - log.debug("create product failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/{productId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"), - @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), }) - public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ProductBusinessLogic businessLogic = getProductBL(context); - log.trace("get product with id {}", productId); - Either<Product, ResponseFormat> actionResponse = businessLogic.getProduct(productId, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to get product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Product"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product"); - log.debug("get product failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/productName/{productName}/productVersion/{productVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") }) - public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - Either<Product, ResponseFormat> actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Product product = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(product); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get product by name and version"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version"); - log.debug("get product failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/products/{productId}") - public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ProductBusinessLogic businessLogic = getProductBL(context); - log.trace("delete product with id {}", productId); - Either<Product, ResponseFormat> actionResponse = businessLogic.deleteProduct(productId, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to delete product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/products/{productId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - - try { - String productIdLower = productId.toLowerCase(); - ProductBusinessLogic businessLogic = getProductBL(context); - Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class); - Either<Product, ResponseFormat> actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to update product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Product product = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(product); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Product Metadata"); - log.debug("update product metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/validate-name/{productName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - - Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get validate service name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name"); - log.debug("validate product name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + private static final Logger log = LoggerFactory.getLogger(ProductServlet.class); + + @POST + @Path("/products") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"), + @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") }) + public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + Product product = RepresentationUtils.fromRepresentation(data, Product.class); + Either<Product, ResponseFormat> actionResponse = businessLogic.createProduct(product, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to create product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product"); + log.debug("create product failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/{productId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"), + @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), }) + public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ProductBusinessLogic businessLogic = getProductBL(context); + log.trace("get product with id {}", productId); + Either<Product, ResponseFormat> actionResponse = businessLogic.getProduct(productId, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to get product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product"); + log.debug("get product failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/productName/{productName}/productVersion/{productVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") }) + public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + Either<Product, ResponseFormat> actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Product product = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(product); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version"); + log.debug("get product failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/products/{productId}") + public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ProductBusinessLogic businessLogic = getProductBL(context); + log.trace("delete product with id {}", productId); + Either<Product, ResponseFormat> actionResponse = businessLogic.deleteProduct(productId, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to delete product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/products/{productId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + + try { + String productIdLower = productId.toLowerCase(); + ProductBusinessLogic businessLogic = getProductBL(context); + Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class); + Either<Product, ResponseFormat> actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to update product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Product product = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(product); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.debug("update product metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/validate-name/{productName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + + Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get validate service name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name"); + log.debug("validate product name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java index bc5ad35c8f..14d2628926 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java @@ -20,29 +20,12 @@ package org.openecomp.sdc.be.servlets; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @@ -64,383 +47,326 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resource Property Servlet", description = "Resource Property Servlet") @Singleton public class PropertyServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(PropertyServlet.class.getName()); - - @POST - @Path("resources/{resourceId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource property already exist") }) - public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - - try { - // convert json to PropertyDefinition - Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map<String, PropertyDefinition> properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next(); - String propertyName = entry.getKey(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // create the new property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to create Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData<String, PropertyDefinition> property = status.left().value(); - String name = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property"); - log.debug("create property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @GET - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}, modifier id is {}", url, userId); - - try { - - // - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId); - - if (status.isRight()) { - log.info("Failed to get Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry<String, PropertyDefinition> property = status.left().value(); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); - log.debug("get property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @DELETE - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userId); - - try { - - // delete the property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); - if (status.isRight()) { - log.debug("Failed to delete Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry<String, PropertyDefinition> property = status.left().value(); - String name = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property"); - log.debug("delete property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @PUT - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - try { - // convert json to PropertyDefinition - Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map<String, PropertyDefinition> properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // update property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to update Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData<String, PropertyDefinition> property = status.left().value(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property"); - log.debug("update property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) { - JSONParser parser = new JSONParser(); - JSONObject root; - try { - Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); - root = (JSONObject) parser.parse(data); - - Set entrySet = root.entrySet(); - Iterator iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Entry next = (Entry) iterator.next(); - String propertyName = (String) next.getKey(); - JSONObject value = (JSONObject) next.getValue(); - String jsonString = value.toJSONString(); - Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); - if (convertJsonToObject.isRight()) { - return Either.right(convertJsonToObject.right().value()); - } - PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); - // PropertyDefinition propertyDefinition = - // gson.fromJson(jsonString , PropertyDefinition.class); - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); - propertyDefinition.setUniqueId(uniqueId); - properties.put(propertyName, propertyDefinition); - } - - // Set keySet = root.keySet(); - // for (Object propertyName : keySet){ - // JSONObject val = (JSONObject) root.get(propertyName); - // String jsonString = val.toJSONString(); - // Either<PropertyDefinition,ActionStatus> convertJsonToObject = - // convertJsonToObject(jsonString, PropertyDefinition.class); - // if (convertJsonToObject.isRight()){ - // return Either.right(convertJsonToObject.right().value()); - // } - // PropertyDefinition propertyDefinition = - // convertJsonToObject.left().value(); - // //PropertyDefinition propertyDefinition = - // gson.fromJson(jsonString , PropertyDefinition.class); - // String uniqueId = - // UniqueIdBuilder.buildPropertyUniqueId("resourceId", - // (String)propertyName); - // propertyDefinition.setUniqueId(uniqueId); - // properties.put((String)propertyName,propertyDefinition); - // } - return Either.left(properties); - } catch (ParseException e) { - log.info("Property conetnt is invalid - {}", data); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } - - private String propertyToJson(Map.Entry<String, PropertyDefinition> property) { - JSONObject root = new JSONObject(); - String propertyName = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - // String jsonPropertyDefinition = gson.toJson(propertyDefinition); - // root.put(propertyName, jsonPropertyDefinition); - JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); - root.put(propertyName, propertyDefinitionO); - propertyDefinition.getType(); - return root.toString(); - } - - private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { - - Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition); - if (either.isRight()) { - return new JSONObject(); - } - String value = either.left().value(); - try { - JSONObject root = (JSONObject) new JSONParser().parse(value); - return root; - } catch (ParseException e) { - log.info("failed to convert input to json"); - log.debug("failed to convert to json", e); - return new JSONObject(); - } - - } - - private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) { - T t = null; - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - try { - log.trace("convert json to object. json=\n {}", data); - t = gson.fromJson(data, clazz); - if (t == null) { - log.info("object is null after converting from json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert from json"); - log.debug("failed to convert from json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(t); - } - - private <T> Either<String, ActionStatus> convertObjectToJson(PropertyDefinition propertyDefinition) { - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); - try { - log.trace("convert object to json. propertyDefinition= {}", propertyDefinition.toString()); - String json = gson.toJson(propertyDefinition); - if (json == null) { - log.info("object is null after converting to json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(json); - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert to json"); - log.debug("failed to convert fto json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - - } - - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); - return propertytBl; - } - - // private class UiProperty{ - // String type; - // String source; - // String name; - // String description; - // public String getType() { - // return type; - // } - // public void setType(String type) { - // this.type = type; - // } - // public String getSource() { - // return source; - // } - // public void setSource(String source) { - // this.source = source; - // } - // public String getName() { - // return name; - // } - // public void setName(String name) { - // this.name = name; - // } - // public String getDescription() { - // return description; - // } - // public void setDescription(String description) { - // this.description = description; - // } - // - // } + private static final Logger log = LoggerFactory.getLogger(PropertyServlet.class); + + @POST + @Path("resources/{resourceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource property already exist") }) + public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + + try { + // convert json to PropertyDefinition + Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data); + if (either.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); + return buildErrorResponse(responseFormat); + } + Map<String, PropertyDefinition> properties = either.left().value(); + if (properties == null || properties.size() != 1) { + log.info("Property conetnt is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next(); + String propertyName = entry.getKey(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + + // create the new property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId); + if (status.isRight()) { + log.info("Failed to create Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + EntryData<String, PropertyDefinition> property = status.left().value(); + String name = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property"); + log.debug("create property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @GET + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}, modifier id is {}", url, userId); + + try { + + // + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId); + + if (status.isRight()) { + log.info("Failed to get Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Entry<String, PropertyDefinition> property = status.left().value(); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, propertyToJson(property)); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); + log.debug("get property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @DELETE + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + try { + + // delete the property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); + if (status.isRight()) { + log.debug("Failed to delete Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Entry<String, PropertyDefinition> property = status.left().value(); + String name = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property"); + log.debug("delete property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @PUT + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + try { + // convert json to PropertyDefinition + Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data); + if (either.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); + return buildErrorResponse(responseFormat); + } + Map<String, PropertyDefinition> properties = either.left().value(); + if (properties == null || properties.size() != 1) { + log.info("Property conetnt is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + + // update property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId); + if (status.isRight()) { + log.info("Failed to update Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + EntryData<String, PropertyDefinition> property = status.left().value(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property"); + log.debug("update property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) { + JSONParser parser = new JSONParser(); + JSONObject root; + try { + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + root = (JSONObject) parser.parse(data); + + Set entrySet = root.entrySet(); + Iterator iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Entry next = (Entry) iterator.next(); + String propertyName = (String) next.getKey(); + JSONObject value = (JSONObject) next.getValue(); + String jsonString = value.toJSONString(); + Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); + if (convertJsonToObject.isRight()) { + return Either.right(convertJsonToObject.right().value()); + } + PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); + propertyDefinition.setUniqueId(uniqueId); + properties.put(propertyName, propertyDefinition); + } + + return Either.left(properties); + } catch (ParseException e) { + log.info("Property conetnt is invalid - {}", data); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } + + private String propertyToJson(Map.Entry<String, PropertyDefinition> property) { + JSONObject root = new JSONObject(); + String propertyName = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); + root.put(propertyName, propertyDefinitionO); + propertyDefinition.getType(); + return root.toString(); + } + + private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { + + Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition); + if (either.isRight()) { + return new JSONObject(); + } + String value = either.left().value(); + try { + JSONObject root = (JSONObject) new JSONParser().parse(value); + return root; + } catch (ParseException e) { + log.info("failed to convert input to json"); + log.debug("failed to convert to json", e); + return new JSONObject(); + } + + } + + private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) { + T t = null; + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + try { + log.trace("convert json to object. json=\n {}", data); + t = gson.fromJson(data, clazz); + if (t == null) { + log.info("object is null after converting from json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert from json"); + log.debug("failed to convert from json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(t); + } + + private <T> Either<String, ActionStatus> convertObjectToJson(PropertyDefinition propertyDefinition) { + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); + try { + log.trace("convert object to json. propertyDefinition= {}", propertyDefinition); + String json = gson.toJson(propertyDefinition); + if (json == null) { + log.info("object is null after converting to json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(json); + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert to json"); + log.debug("failed to convert fto json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + + } + + private PropertyBusinessLogic getPropertyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); + return propertytBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java index 98e966e6eb..da42fe2b6f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java @@ -20,14 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.io.IOException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; @@ -36,132 +35,126 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import java.io.IOException; +import com.fasterxml.jackson.databind.SerializationFeature; public class RepresentationUtils { - private static Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName()); - - public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) { - - JsonObject jsonElement = new JsonObject(); - ArtifactDefinition resourceInfo = null; - - try { - Gson gson = new Gson(); - jsonElement = gson.fromJson(content, jsonElement.getClass()); - String payload = null; - jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD); - //in update the group type is ignored but this spagheti code makes it too complex to remove this field. - jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); - JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); - if (artifactPayload != null && !artifactPayload.isJsonNull()) { - payload = artifactPayload.getAsString(); - } - jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - String json = gson.toJson(jsonElement); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - resourceInfo = mapper.readValue(json, clazz); - resourceInfo.setPayloadData(payload); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); - BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return resourceInfo; - } - - - public static class ResourceRep { - - } - - /** - * Build Representation of given Object - * - * @param elementToRepresent - * @return - * @throws IOException - * @throws JsonGenerationException - * @throws JsonMappingException - */ - public static <T> Object toRepresentation(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException { - - // return theResource; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - return mapper.writeValueAsString(elementToRepresent); - } - - public static <T> T fromRepresentation(String json, Class<T> clazz) { - ObjectMapper mapper = new ObjectMapper(); - T object = null; - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - try { - object = mapper.readValue(json, clazz); - } catch (Exception e) { - log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); - } // return null in case of exception - - return object; - } - - public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) { - - JsonObject jsonElement = new JsonObject(); - ArtifactDefinition resourceInfo = null; - - try { - Gson gson = new Gson(); - jsonElement = gson.fromJson(content, jsonElement.getClass()); - JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE_FIELD); - if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { - String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); - if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { - StringBuilder sb = new StringBuilder(); - for (String value : ArtifactGroupTypeEnum.getAllTypes()) { - sb.append(value).append(", "); - } - log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb.toString()); - return null; - } else { - jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD); - jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, groupValueUpper); - } - } - String payload = null; - JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); - if (artifactPayload != null && !artifactPayload.isJsonNull()) { - payload = artifactPayload.getAsString(); - } - jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - String json = gson.toJson(jsonElement); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - resourceInfo = mapper.readValue(json, clazz); - resourceInfo.setPayloadData(payload); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); - BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return resourceInfo; - } + private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class); + + public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) { + + JsonObject jsonElement = new JsonObject(); + ArtifactDefinition resourceInfo = null; + + try { + Gson gson = new Gson(); + jsonElement = gson.fromJson(content, jsonElement.getClass()); + String payload = null; + jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE); + //in update the group type is ignored but this spagheti code makes it too complex to remove this field. + jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + resourceInfo = mapper.readValue(json, clazz); + resourceInfo.setPayloadData(payload); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return resourceInfo; + } + + + public static class ResourceRep { + + } + + /** + * Build Representation of given Object + * + * @param elementToRepresent + * @return + * @throws IOException + */ + public static <T> Object toRepresentation(T elementToRepresent) throws IOException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(elementToRepresent); + } + + public static <T> T fromRepresentation(String json, Class<T> clazz) { + ObjectMapper mapper = new ObjectMapper(); + T object = null; + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + try { + object = mapper.readValue(json, clazz); + } catch (Exception e) { + log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); + } // return null in case of exception + + return object; + } + + public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) { + + JsonObject jsonElement = new JsonObject(); + ArtifactDefinition resourceInfo = null; + + try { + Gson gson = new Gson(); + jsonElement = gson.fromJson(content, jsonElement.getClass()); + JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE); + if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { + String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); + if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { + StringBuilder sb = new StringBuilder(); + for (String value : ArtifactGroupTypeEnum.getAllTypes()) { + sb.append(value).append(", "); + } + log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb); + return null; + } else { + jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE); + jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, groupValueUpper); + } + } + String payload = null; + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + resourceInfo = mapper.readValue(json, clazz); + resourceInfo.setPayloadData(payload); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return resourceInfo; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java index fb4aba6af7..e8769cca9b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java @@ -20,66 +20,56 @@ package org.openecomp.sdc.be.servlets; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonSyntaxException; import com.jcabi.aspects.Loggable; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) public class RequirementsServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(RequirementsServlet.class.getName()); - - @PUT - @Path("resources/{resourceId}/requirements/{requirementId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + private static final Logger log = LoggerFactory.getLogger(RequirementsServlet.class); - // Convert RequirementDefinition from JSON - // TODO: it's going to be another object, probably. This is placeholder - // for sake of JSON validation - // RequirementDefinition requirementDefinition; - ResponseFormat responseFormat; - try { - // requirementDefinition = gson.fromJson(requirementData, - // RequirementDefinition.class); - // ..... + @PUT + @Path("resources/{resourceId}/requirements/{requirementId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - // TODO pass real entity - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - } catch (JsonSyntaxException e) { - // INVALID JSON - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } catch (Exception e) { - log.debug("Unexpected error: {}", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - } + // Convert RequirementDefinition from JSON + // TODO: it's going to be another object, probably. This is placeholder + // for sake of JSON validation + // RequirementDefinition requirementDefinition; + ResponseFormat responseFormat; + try { + // TODO pass real entity + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + } catch (Exception e) { + log.debug("Unexpected error: ", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java index 54ec6e3b15..5d4001eec5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java @@ -20,15 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -38,116 +33,116 @@ import org.openecomp.sdc.be.info.ArtifactAccessInfo; import org.openecomp.sdc.be.resources.api.IResourceUploader; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/resources/available") public class ResourceArtifactDownloadServlet extends ToscaDaoServlet { - private static Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class.getName()); - - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @GET - @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}") - // @Produces(MediaType.APPLICATION_OCTET_STREAM) - public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - try { - // get the artifact data - String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); - - IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext()); - if (resouceUploader == null) { - return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); - - } - Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resouceUploader.getArtifact(artifactId); - - DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext()); - if (logic == null) { - return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); - - } - response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId); - - log.info("Finish handle request of {} | result = {}", url, response.getStatus()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact By Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name"); - log.debug("getResourceArtifactByName failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata") - @Produces(MediaType.APPLICATION_JSON) - public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Response response = null; - try { - IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext()); - if (resourceDao == null) { - log.error("resource dao cannot be found"); - response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found"); - return response; - } - - String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); - Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resourceDao.getArtifact(artifactId); - - if (getArtifactStatus.isRight()) { - ResourceUploadStatus status = getArtifactStatus.right().value(); - if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) { - response = Response.status(HttpStatus.SC_NOT_FOUND).build(); - log.debug("Could not find artifact for with id: {}", artifactId); - } else { - response = Response.status(HttpStatus.SC_NO_CONTENT).build(); - log.debug("Could not find artifact for with id: {}", artifactId); - } - return response; - } else { - ESArtifactData artifactData = getArtifactStatus.left().value(); - log.debug("found artifact with id: {}", artifactId); - ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData); - String artifactDataJson = gson.toJson(artifactInfo); - response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); - - log.info("Finish handle request of {} | result = {}", url, response.getStatus()); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata"); - log.debug("getResourceArtifactMetadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - - } - - @Override - public Logger getLogger() { - return log; - } + private static final Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class); + + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @GET + @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}") + // @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + try { + // get the artifact data + String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); + + IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext()); + if (resouceUploader == null) { + return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); + + } + Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resouceUploader.getArtifact(artifactId); + + DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext()); + if (logic == null) { + return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); + + } + response = logic.downloadArtifact(artifactName, getArtifactStatus, artifactId); + + log.info("Finish handle request of {} | result = {}", url, response.getStatus()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name"); + log.debug("getResourceArtifactByName failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata") + @Produces(MediaType.APPLICATION_JSON) + public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Response response = null; + try { + IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext()); + if (resourceDao == null) { + log.error("resource dao cannot be found"); + response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found"); + return response; + } + + String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); + Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resourceDao.getArtifact(artifactId); + + if (getArtifactStatus.isRight()) { + ResourceUploadStatus status = getArtifactStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) { + response = Response.status(HttpStatus.SC_NOT_FOUND).build(); + log.debug("Could not find artifact for with id: {}", artifactId); + } else { + response = Response.status(HttpStatus.SC_NO_CONTENT).build(); + log.debug("Could not find artifact for with id: {}", artifactId); + } + return response; + } else { + ESArtifactData artifactData = getArtifactStatus.left().value(); + log.debug("found artifact with id: {}", artifactId); + ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData); + String artifactDataJson = gson.toJson(artifactInfo); + response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); + + log.info("Finish handle request of {} | result = {}", url, response.getStatus()); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata"); + log.debug("getResourceArtifactMetadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + + } + + @Override + public Logger getLogger() { + return log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java index 3cf2a69fb5..2508423d03 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java @@ -20,24 +20,8 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; - -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.*; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -53,13 +37,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; /** * Root resource (exposed at "/" path) @@ -70,115 +56,114 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ResourceUploadServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName()); - public static final String NORMATIVE_TYPE_RESOURCE = "multipart"; - public static final String CSAR_TYPE_RESOURCE = "csar"; - public static final String USER_TYPE_RESOURCE = "user-resource"; - public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import"; - - public enum ResourceAuthorityTypeEnum { - NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true); - - private String urlPath; - private boolean isBackEndImport, isUserTypeResource; - - public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) { - ResourceAuthorityTypeEnum found = null; - for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) { - if (curr.getUrlPath().equals(urlPath)) { - found = curr; - break; - } - } - return found; - } - - private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) { - this.urlPath = urlPath; - this.isBackEndImport = isBackEndImport; - this.isUserTypeResource = isUserTypeResource; - } - - public String getUrlPath() { - return urlPath; - } - - public boolean isBackEndImport() { - return isBackEndImport; - } - - public boolean isUserTypeResource() { - return isUserTypeResource; - } - } - - @Resource - private ResourceImportManager resourceImportManager; - - @POST - @Path("/{resourceAuthority}") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response uploadMultipart( - @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + "," - + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority, - @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, - @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - // updateResourse Query Parameter if false checks if already exist - @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) { - - init(request.getSession().getServletContext()); - try { - - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<User> userWrapper = new Wrapper<>(); - Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>(); - Wrapper<String> yamlStringWrapper = new Wrapper<>(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // When we get an errorResponse it will be filled into the - // responseWrapper - validateAuthorityType(responseWrapper, resourceAuthority); - - ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority); - - commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); - - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file); - - // PayLoad Validations - if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ - commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); - - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); - } - - if (responseWrapper.isEmpty()) { - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Upload Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource"); - log.debug("upload resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /********************************************************************************************************************/ - - private void init(ServletContext context) { - init(log); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); - resourceImportManager.init(context); - } + private static final Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class); + public static final String NORMATIVE_TYPE_RESOURCE = "multipart"; + public static final String CSAR_TYPE_RESOURCE = "csar"; + public static final String USER_TYPE_RESOURCE = "user-resource"; + public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import"; + + public enum ResourceAuthorityTypeEnum { + NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true); + + private String urlPath; + private boolean isBackEndImport, isUserTypeResource; + + public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) { + ResourceAuthorityTypeEnum found = null; + for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) { + if (curr.getUrlPath().equals(urlPath)) { + found = curr; + break; + } + } + return found; + } + + private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) { + this.urlPath = urlPath; + this.isBackEndImport = isBackEndImport; + this.isUserTypeResource = isUserTypeResource; + } + + public String getUrlPath() { + return urlPath; + } + + public boolean isBackEndImport() { + return isBackEndImport; + } + + public boolean isUserTypeResource() { + return isUserTypeResource; + } + } + + @Resource + private ResourceImportManager resourceImportManager; + + @POST + @Path("/{resourceAuthority}") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response uploadMultipart( + @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + "," + + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority, + @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, + @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + // updateResourse Query Parameter if false checks if already exist + @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) { + + init(request.getSession().getServletContext()); + try { + + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<User> userWrapper = new Wrapper<>(); + Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>(); + Wrapper<String> yamlStringWrapper = new Wrapper<>(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // When we get an errorResponse it will be filled into the + // responseWrapper + validateAuthorityType(responseWrapper, resourceAuthority); + + ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority); + + commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); + + fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file); + + // PayLoad Validations + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); + + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + } + + if (responseWrapper.isEmpty()) { + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource"); + log.debug("upload resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /********************************************************************************************************************/ + + private void init(ServletContext context) { + init(log); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); + resourceImportManager.init(context); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java index 8aa5093404..db0d4fb537 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java @@ -20,29 +20,9 @@ package org.openecomp.sdc.be.servlets; -import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.http.HttpStatus; import org.json.JSONObject; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; @@ -66,622 +46,586 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resources Catalog", description = "Resources Servlet") @Singleton public class ResourcesServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ResourcesServlet.class.getName()); - - @POST - @Path("/resources") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - - Wrapper<Response> responseWrapper = new Wrapper<>(); - // UI Import - if (isUIImport(data)) { - performUIImport(responseWrapper, data, request, userId, null); - } - // UI Create - else { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse resource"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Resource resource = convertResponse.left().value(); - Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); - - if (actionResponse.isRight()) { - log.debug("failed to create resource"); - response = buildErrorResponse(actionResponse.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); - } - responseWrapper.setInnerElement(response); - } - - return responseWrapper.getInnerElement(); - - // return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource"); - log.debug("create resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - private boolean isUIImport(String data) { - boolean isUIImport; - try { - JSONObject json = new JSONObject(data); - String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME); - isUIImport = payloadName != null && !payloadName.isEmpty(); - } catch (Exception e) { - log.debug("failed to parse json sent from client, json:{}", data, e); - isUIImport = false; - } - return isUIImport; - } - - private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException { - - Wrapper<User> userWrapper = new Wrapper<>(); - Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>(); - Wrapper<String> yamlStringWrapper = new Wrapper<>(); - String resourceInfoJsonString = data; - - ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI; - - commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); - - if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null); - - // PayLoad Validations - commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); - } - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); - - if (responseWrapper.isEmpty()) { - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); - } - } - - public Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); - } - - public Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) { - Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); - if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow) - ret.left().value().setRequirements(null); - ret.left().value().setCapabilities(null); - } - return ret; - } - - @DELETE - @Path("/resources/{resourceId}") - public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = resourceId.toLowerCase(); - ResourceBusinessLogic businessLogic = getResourceBL(context); - ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete resource"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @DELETE - @Path("/resources/{resourceName}/{version}") - public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete resource"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/resources/{resourceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = resourceId.toLowerCase(); - ResourceBusinessLogic businessLogic = getResourceBL(context); - log.trace("get resource with id {}", resourceId); - Either<Resource, ResponseFormat> actionResponse = businessLogic.getResource(resourceIdLower, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get resource"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - Response response = null; - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource by name and version"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/resources/validate-name/{resourceName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - Response response = null; - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - - if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) { - log.debug("invalid resource type received"); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - return response; - - } - ResourceTypeEnum typeEnum = null; - if (resourceType != null) { - typeEnum = ResourceTypeEnum.valueOf(resourceType); - } - Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId); - - if (actionResponse.isRight()) { - log.debug("failed to validate resource name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Resource Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name"); - log.debug("validate resource name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/resources/certified/abstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - // TODO: any validations??? - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); - Response response = null; - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all abstract resources"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Abstract Resources"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources"); - log.debug("getCertifiedAbstractResources failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/resources/certified/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - // TODO: any vlidations??? - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); - Response response = null; - - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract resources"); - return buildErrorResponse(actionResponse.right().value()); - } - Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract Resources"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources"); - log.debug("getCertifiedNotAbstractResources failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @PUT - @Path("/resources/{resourceId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") }) - public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - String resourceIdLower = resourceId.toLowerCase(); - Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); - if (updateInfoResource.isRight()) { - log.debug("failed to parse resource metadata"); - response = buildErrorResponse(updateInfoResource.right().value()); - return response; - } - Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); - - if (actionResponse.isRight()) { - log.debug("failed to update resource metadata"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata"); - log.debug("Update Resource Metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/resources/{resourceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @PathParam(value = "resourceId") String resourceId) { - - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - - Wrapper<Response> responseWrapper = new Wrapper<>(); - // UI Import - if (isUIImport(data)) { - performUIImport(responseWrapper, data, request, userId, resourceId); - } else { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse resource"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Resource resource = convertResponse.left().value(); - Either<Resource, ResponseFormat> actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId); - - if (actionResponse.isRight()) { - log.debug("failed to update resource"); - response = buildErrorResponse(actionResponse.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); - } - responseWrapper.setInnerElement(response); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource"); - log.debug("update resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* - * @GET - * - * @Path("/resources/latestversion/notabstract") - * - * @Consumes(MediaType.APPLICATION_JSON) - * - * @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionNotAbstractResources(@Context final HttpServletRequest request) { //TODO: any vlidations??? ServletContext context = request.getSession().getServletContext(); - * - * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null; - * - * try { - * - * ResourceBusinessLogic businessLogic = getResourceBL(context); - * - * Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getLatestVersionResources(false, HighestFilterEnum.HIGHEST_ONLY); - * - * - * if (actionResponse.isRight()){ log.debug( "failed to get all non abstract resources"); return buildErrorResponse(actionResponse.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - * actionResponse.left().value()); - * - * } catch (Exception e){ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Get Certified Non Abstract Resources"); log.debug("getCertifiedNotAbstractResources failed with exception", e); response = - * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response; - * - * } } - */ - public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) { - if (properties == null) { - return null; - } - - List<PropertyDefinition> definitions = new ArrayList<>(); - for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { - String name = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - definitions.add(propertyDefinition); - } - - return definitions; - } - - @GET - @Path("/resources/csar/{csaruuid}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) { - - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // retrieve user details - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - User user = new User(); - user.setUserId(userId); - - log.debug("user id is {}", userId); - - Response response = null; - - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either<Resource, ResponseFormat> eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user); - - // validate response - if (eitherResource.isRight()) { - log.debug("failed to get resource from csarUuid : {}", csarUUID); - // response = - // buildErrorResponse(eitherResource.right().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); - } - - return response; - - } catch (Exception e) { - log.debug("get resource by csar failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } + private static final Logger log = LoggerFactory.getLogger(ResourcesServlet.class); + + @POST + @Path("/resources") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + + Wrapper<Response> responseWrapper = new Wrapper<>(); + // UI Import + if (isUIImport(data)) { + performUIImport(responseWrapper, data, request, userId, null); + } + // UI Create + else { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse resource"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Resource resource = convertResponse.left().value(); + Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); + + if (actionResponse.isRight()) { + log.debug("failed to create resource"); + response = buildErrorResponse(actionResponse.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); + } + responseWrapper.setInnerElement(response); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource"); + log.debug("create resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private boolean isUIImport(String data) { + boolean isUIImport; + try { + JSONObject json = new JSONObject(data); + String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME); + isUIImport = payloadName != null && !payloadName.isEmpty(); + } catch (Exception e) { + log.debug("failed to parse json sent from client, json:{}", data, e); + isUIImport = false; + } + return isUIImport; + } + + private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException { + + Wrapper<User> userWrapper = new Wrapper<>(); + Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>(); + Wrapper<String> yamlStringWrapper = new Wrapper<>(); + String resourceInfoJsonString = data; + + ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI; + + commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); + + if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { + fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null); + + // PayLoad Validations + commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); + } + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + + if (responseWrapper.isEmpty()) { + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); + } + } + + public Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); + } + + public Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) { + Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow) + ret.left().value().setRequirements(null); + ret.left().value().setCapabilities(null); + } + return ret; + } + + @DELETE + @Path("/resources/{resourceId}") + public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + String resourceIdLower = resourceId.toLowerCase(); + ResourceBusinessLogic businessLogic = getResourceBL(context); + ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete resource"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @DELETE + @Path("/resources/{resourceName}/{version}") + public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete resource"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/resources/{resourceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + String resourceIdLower = resourceId.toLowerCase(); + ResourceBusinessLogic businessLogic = getResourceBL(context); + log.trace("get resource with id {}", resourceId); + Either<Resource, ResponseFormat> actionResponse = businessLogic.getResource(resourceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get resource"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + Response response = null; + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/resources/validate-name/{resourceName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + Response response = null; + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + + if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) { + log.debug("invalid resource type received"); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + return response; + + } + ResourceTypeEnum typeEnum = null; + if (resourceType != null) { + typeEnum = ResourceTypeEnum.valueOf(resourceType); + } + Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId); + + if (actionResponse.isRight()) { + log.debug("failed to validate resource name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name"); + log.debug("validate resource name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/resources/certified/abstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + // TODO: any validations??? + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}" , url); + Response response = null; + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all abstract resources"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources"); + log.debug("getCertifiedAbstractResources failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/resources/certified/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + // TODO: any vlidations??? + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}" , url); + Response response = null; + + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract resources"); + return buildErrorResponse(actionResponse.right().value()); + } + Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources"); + log.debug("getCertifiedNotAbstractResources failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @PUT + @Path("/resources/{resourceId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") }) + public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + String resourceIdLower = resourceId.toLowerCase(); + Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + if (updateInfoResource.isRight()) { + log.debug("failed to parse resource metadata"); + response = buildErrorResponse(updateInfoResource.right().value()); + return response; + } + Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); + + if (actionResponse.isRight()) { + log.debug("failed to update resource metadata"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata"); + log.debug("Update Resource Metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/resources/{resourceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @PathParam(value = "resourceId") String resourceId) { + + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + + Wrapper<Response> responseWrapper = new Wrapper<>(); + // UI Import + if (isUIImport(data)) { + performUIImport(responseWrapper, data, request, userId, resourceId); + } else { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse resource"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Resource resource = convertResponse.left().value(); + Either<Resource, ResponseFormat> actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId); + + if (actionResponse.isRight()) { + log.debug("failed to update resource"); + response = buildErrorResponse(actionResponse.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); + } + responseWrapper.setInnerElement(response); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource"); + log.debug("update resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) { + if (properties == null) { + return null; + } + + List<PropertyDefinition> definitions = new ArrayList<>(); + for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { + String name = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + definitions.add(propertyDefinition); + } + + return definitions; + } + + @GET + @Path("/resources/csar/{csaruuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) { + + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // retrieve user details + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + User user = new User(); + user.setUserId(userId); + + log.debug("user id is {}", userId); + + Response response = null; + + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either<Resource, ResponseFormat> eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user); + + // validate response + if (eitherResource.isRight()) { + log.debug("failed to get resource from csarUuid : {}", csarUUID); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); + } + + return response; + + } catch (Exception e) { + log.debug("get resource by csar failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java new file mode 100644 index 0000000000..f794e8c90b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java @@ -0,0 +1,243 @@ +package org.openecomp.sdc.be.servlets; + +import com.google.common.collect.Sets; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import java.util.Collections; +import java.util.Set; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog/services/{serviceId}/paths") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +@Api(value = "Service Forwarding Path", description = "Service Forwarding Path Servlet") +@Singleton +public class ServiceForwardingPathServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(ServiceForwardingPathServlet.class); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @ApiOperation(value = "Create Forwarding Path", httpMethod = "POST", notes = "Create Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Create Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response createForwardingPath( + @ApiParam(value = "Forwarding Path to create", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, serviceId, request, userId, false); + } + + + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @ApiOperation(value = "Update Forwarding Path", httpMethod = "PUT", notes = "Update Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Update Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response updateForwardingPath( + @ApiParam(value = "Update Path to create", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, serviceId, request, userId, true); + } + + private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + Service updatedService = convertResponse.left().value(); + Either<Service, ResponseFormat> actionResponse ; + if (isUpdate) { + actionResponse = businessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true); + } else { + actionResponse = businessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true); + } + + if (actionResponse.isRight()) { + log.debug("failed to update or create paths"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update"); + log.debug("create or update forwarding path with an error", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/{forwardingPathId}") + @ApiOperation(value = "Get Forwarding Path", httpMethod = "GET", notes = "GET Forwarding Path", response = ForwardingPathDataDefinition.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Get Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response getForwardingPath( + @ApiParam(value = "Forwarding Path to create", required = true) String datax, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = businessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + if (serviceResponse.isRight()) { + return buildErrorResponse(serviceResponse.right().value()); + } + + UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value(); + + ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition(); + if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) { + forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition)); + + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); + log.debug("update service metadata failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/{forwardingPathId}") + @ApiOperation(value = "Delete Forwarding Path", httpMethod = "DELETE", notes = "Delete Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Delete Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response deleteForwardingPath( + @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either<Set<String>, ResponseFormat> actionResponse = businessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true); + + if (actionResponse.isRight()) { + log.debug("failed to delete paths"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Set<String> deletedPaths = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(deletedPaths); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths"); + log.debug("Delete service paths with an error", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + + private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java index cb90d89ed9..49a1a82e59 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java @@ -20,47 +20,19 @@ package org.openecomp.sdc.be.servlets; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Type; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.http.HttpStatus; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.ServiceRelations; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.GroupInstanceProperty; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; @@ -68,15 +40,17 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -84,692 +58,629 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ServiceServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ServiceServlet.class.getName()); - - @POST - @Path("/services") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Service already exist") }) - public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse service"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Service service = convertResponse.left().value(); - Either<Service, ResponseFormat> actionResponse = businessLogic.createService(service, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to create service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service"); - log.debug("create service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - - @GET - @Path("/services/validate-name/{serviceName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - - Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get validate service name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); - log.debug("validate service name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/audit-records/{componentType}/{componentUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - init(log); - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Wrapper<Response> responseWrapper = new Wrapper<Response>(); - Wrapper<String> uuidWrapper = new Wrapper<>(); - Wrapper<String> versionWrapper = new Wrapper<>(); - Wrapper<User> userWrapper = new Wrapper<>(); - Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<ComponentTypeEnum>(); - try { - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - validateComponentType(responseWrapper, componentWrapper, componentType); - } - - if (responseWrapper.isEmpty()) { - fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context); - } - - if (responseWrapper.isEmpty()) { - Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); - - if (eitherServiceAudit.isRight()) { - Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value()); - responseWrapper.setInnerElement(errorResponse); - } else { - List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value(); - Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords); - responseWrapper.setInnerElement(okResponse); - - } - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); - log.debug("get Service Audit Records failed with exception", e); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - } - return responseWrapper.getInnerElement(); - } - - private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) { - - if (componentTypeEnum == ComponentTypeEnum.RESOURCE) { - Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user); - if (eitherResource.isLeft()) { - uuidWrapper.setInnerElement(eitherResource.left().value().getUUID()); - versionWrapper.setInnerElement(eitherResource.left().value().getVersion()); - } else { - responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value())); - } - - } else { - Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user); - if (eitherService.isLeft()) { - uuidWrapper.setInnerElement(eitherService.left().value().getUUID()); - versionWrapper.setInnerElement(eitherService.left().value().getVersion()); - } else { - responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value())); - - } - } - } - - @DELETE - @Path("/services/{serviceId}") - public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete service"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); - log.debug("delete service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @DELETE - @Path("/services/{serviceName}/{version}") - public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete service"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); - log.debug("delete service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/services/{serviceId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - - Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse service"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - Service updatedService = convertResponse.left().value(); - Either<Service, ResponseFormat> actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to update service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); - log.debug("update service metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - /** - * updates group instance property values - * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated - * @param serviceId - * @param componentInstanceId - * @param groupInstanceId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Response response = null; - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}",userId); - - ServiceBusinessLogic businessLogic; - Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null; - try { - List<GroupInstanceProperty> updatedProperties; - Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType(); - ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType); - if (newProperties == null) { - actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if(actionResponse == null){ - log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); - businessLogic = getServiceBL(context); - actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); - if(actionResponse.isRight()){ - actionResponse = Either.right(actionResponse.right().value()); - } - } - if(actionResponse.isLeft()){ - updatedProperties = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(updatedProperties); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } - else{ - response = buildErrorResponse(actionResponse.right().value()); - } - } catch (Exception e) { - log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return response; - } - - @GET - @Path("/services/{serviceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - log.debug("get service with id {}", serviceId); - Either<Service, ResponseFormat> actionResponse = businessLogic.getService(serviceIdLower, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); - log.debug("get service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either<Service, ResponseFormat> actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version"); - log.debug("get service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @POST - @Path("/services/{serviceId}/distribution-state/{state}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId, - @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either<Service, ResponseFormat> actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to Update Service Distribution State"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State"); - log.debug("updateServiceDistributionState failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/distribution/{env}/activate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution") - @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"), - @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either<Service, ResponseFormat> distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request); - - if (distResponse.isRight()) { - log.debug("failed to activate service distribution"); - response = buildErrorResponse(distResponse.right().value()); - return response; - } - Service service = distResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); - log.debug("activate distribution failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/distribution/{did}/markDeployed") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either<Service, ResponseFormat> distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier); - - if (distResponse.isRight()) { - log.debug("failed to mark distribution as deployed"); - response = buildErrorResponse(distResponse.right().value()); - return response; - } - Service service = distResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed"); - log.debug("mark distribution as deployed failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/tempUrlToBeDeleted") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Service service = (businessLogic.getService(serviceId, modifier)).left().value(); - Either<Service, ResponseFormat> res = (businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED)); - - if (res.isRight()) { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted"); - log.debug("failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/services/toscatoheat/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Artifact not found") }) - public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) { - Response response = null; - - try { - log.debug("artifact name = {}", artifactName); - - Either<byte[], ResponseFormat> executeCommand = executeCommand(artifactName); - - if (executeCommand.isRight()) { - log.debug("Failed to convert tosca {} to heat", artifactName); - ResponseFormat responseFormat = executeCommand.right().value(); - response = buildErrorResponse(responseFormat); - } else { - log.debug("Succeed to convert tosca {} to heat", artifactName); - byte[] value = executeCommand.left().value(); - InputStream is = new ByteArrayInputStream(value); - - Map<String, String> headers = new HashMap<>(); - String heatFileName; - if (artifactName.indexOf(".") > -1) { - heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat"; - } else { - heatFileName = artifactName + ".heat"; - } - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(heatFileName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, is, headers); - } - return response; - - } catch (Exception e) { - log.error("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private Either<byte[], ResponseFormat> executeCommand(String artifactName) { - - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - String toscaFilesDir = configuration.getToscaFilesDir(); - if (toscaFilesDir == null) { - toscaFilesDir = "/apps/jetty/base/be/config/tosca"; - } - String heatTranslator = configuration.getHeatTranslatorPath(); - if (heatTranslator == null) { - heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py"; - } - - log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator); - - StringBuffer output = new StringBuffer(); - - String heatHeader = configuration.getHeatEnvArtifactHeader(); - String heatFooter = configuration.getHeatEnvArtifactFooter(); - - output.append(heatHeader + "\n"); - - MessageFormat mf = new MessageFormat("python {0} --template-file={1}/{2} --template-type=tosca"); - - log.debug("After creating message format"); - - Object[] objArray = { heatTranslator, toscaFilesDir, artifactName }; - String command = null; - try { - command = mf.format(objArray); - } catch (Exception e) { - log.debug("Failed to convert message format", e); - } - - log.debug("Going to run command {}", command); - - Process p; - try { - p = Runtime.getRuntime().exec(command); - int waitFor = p.waitFor(); - log.debug("waitFor = {}", waitFor); - - if (waitFor != 0) { - log.error("Failed runnign the command {}", command); - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - - String line; - while ((line = reader.readLine()) != null) { - output.append(line + "\n"); - } - - } catch (Exception e) { - log.error("Failed runnign the command {}", command, e); - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - output.append(heatFooter); - - return Either.left(output.toString().getBytes()); - - } + private static final Logger log = LoggerFactory.getLogger(ServiceServlet.class); + + @POST + @Path("/services") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Service already exist") }) + public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Service service = convertResponse.left().value(); + Either<Service, ResponseFormat> actionResponse = businessLogic.createService(service, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to create service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service"); + log.debug("create service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + } + + @GET + @Path("/services/validate-name/{serviceName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get validate service name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); + log.debug("validate service name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/audit-records/{componentType}/{componentUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + init(log); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Wrapper<Response> responseWrapper = new Wrapper<Response>(); + Wrapper<String> uuidWrapper = new Wrapper<>(); + Wrapper<String> versionWrapper = new Wrapper<>(); + Wrapper<User> userWrapper = new Wrapper<>(); + Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<ComponentTypeEnum>(); + try { + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + validateComponentType(responseWrapper, componentWrapper, componentType); + } + + if (responseWrapper.isEmpty()) { + fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context); + } + + if (responseWrapper.isEmpty()) { + Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); + + if (eitherServiceAudit.isRight()) { + Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value()); + responseWrapper.setInnerElement(errorResponse); + } else { + List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value(); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords); + responseWrapper.setInnerElement(okResponse); + + } + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); + log.debug("get Service Audit Records failed with exception", e); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + } + return responseWrapper.getInnerElement(); + } + + private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) { + + if (componentTypeEnum == ComponentTypeEnum.RESOURCE) { + Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user); + if (eitherResource.isLeft()) { + uuidWrapper.setInnerElement(eitherResource.left().value().getUUID()); + versionWrapper.setInnerElement(eitherResource.left().value().getVersion()); + } else { + responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value())); + } + + } else { + Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user); + if (eitherService.isLeft()) { + uuidWrapper.setInnerElement(eitherService.left().value().getUUID()); + versionWrapper.setInnerElement(eitherService.left().value().getVersion()); + } else { + responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value())); + + } + } + } + + @DELETE + @Path("/services/{serviceId}") + public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete service"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); + log.debug("delete service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @DELETE + @Path("/services/{serviceName}/{version}") + public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete service"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); + log.debug("delete service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/services/{serviceId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + Service updatedService = convertResponse.left().value(); + Either<Service, ResponseFormat> actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to update service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); + log.debug("update service metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + /** + * updates group instance property values + * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Response response = null; + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}",userId); + + ServiceBusinessLogic businessLogic; + Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null; + try { + List<GroupInstanceProperty> updatedProperties; + Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType(); + ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType); + if (newProperties == null) { + actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if(actionResponse == null){ + log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); + businessLogic = getServiceBL(context); + actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); + if(actionResponse.isRight()){ + actionResponse = Either.right(actionResponse.right().value()); + } + } + if(actionResponse.isLeft()){ + updatedProperties = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(updatedProperties); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } + else{ + response = buildErrorResponse(actionResponse.right().value()); + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return response; + } + + @GET + @Path("/services/{serviceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + log.debug("get service with id {}", serviceId); + Either<Service, ResponseFormat> actionResponse = businessLogic.getService(serviceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); + log.debug("get service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<Service, ResponseFormat> actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version"); + log.debug("get service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @POST + @Path("/services/{serviceId}/distribution-state/{state}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId, + @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<Service, ResponseFormat> actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to Update Service Distribution State"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State"); + log.debug("updateServiceDistributionState failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/distribution/{env}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution") + @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"), + @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<Service, ResponseFormat> distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request); + + if (distResponse.isRight()) { + log.debug("failed to activate service distribution"); + response = buildErrorResponse(distResponse.right().value()); + return response; + } + Service service = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); + log.debug("activate distribution failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/distribution/{did}/markDeployed") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either<Service, ResponseFormat> distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier); + + if (distResponse.isRight()) { + log.debug("failed to mark distribution as deployed"); + response = buildErrorResponse(distResponse.right().value()); + return response; + } + Service service = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed"); + log.debug("mark distribution as deployed failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/tempUrlToBeDeleted") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Service service = (businessLogic.getService(serviceId, modifier)).left().value(); + Either<Service, ResponseFormat> res = businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED); + + if (res.isRight()) { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted"); + log.debug("failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + @GET + @Path("/services/{serviceId}/linksMap") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service component relations map", httpMethod = "GET", notes = "Returns service components relations", response = ServiceRelations.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + log.debug("get service components relations with id {}", serviceId); + Either<ServiceRelations, ResponseFormat> actionResponse = businessLogic.getServiceComponentsRelations(serviceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get service relations data"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + ServiceRelations serviceRelations = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(serviceRelations); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); + log.debug("get service relations data failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java new file mode 100644 index 0000000000..fce8dd009e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java @@ -0,0 +1,36 @@ +package org.openecomp.sdc.be.servlets; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class StorageExceptionMapper implements ExceptionMapper<StorageException> { + + private final ComponentsUtils componentsUtils; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public StorageExceptionMapper(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @Override + public Response toResponse(StorageException exception) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(exception.getStorageOperationStatus()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Response.status(responseFormat.getStatus()) + .entity(gson.toJson(responseFormat.getRequestError())) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java index eea2bfdc42..a30cd3c7b2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.ws.rs.core.Response; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -33,60 +30,45 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.ws.rs.core.Response; + public abstract class ToscaDaoServlet extends BeGenericServlet { - public abstract Logger getLogger(); - - protected IResourceUploader getResourceUploader(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - if (webApplicationContextWrapper == null) { - getLogger().error("Failed to get web application context from context."); - return null; - } - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(IResourceUploader.class); - - } - - // protected IToscaYamlBuilder getToscaYamlBuilder(ServletContext context){ - // WebAppContextWrapper webApplicationContextWrapper = - // (WebAppContextWrapper) context - // .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - // - // if (webApplicationContextWrapper == null) { - // getLogger().error("Failed to get web application context from context."); - // return null; - // } - // - // WebApplicationContext webApplicationContext = - // webApplicationContextWrapper - // .getWebAppContext(context); - // - // return webApplicationContext.getBean(IToscaYamlBuilder.class); - // - // } - - protected DownloadArtifactLogic getLogic(ServletContext context) { - DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR); - - if (downloadLogic == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInitializationError, "DownloadArtifactLogic from context"); - BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context"); - return null; - } - return downloadLogic; - } - - protected Response buildResponse(int status, String errorMessage) { - - ServletJsonResponse jsonResponse = new ServletJsonResponse(); - jsonResponse.setDescription(errorMessage); - jsonResponse.setSource(Constants.CATALOG_BE); - - Response response = Response.status(status).entity(jsonResponse).build(); - - return response; - } + public abstract Logger getLogger(); + + protected IResourceUploader getResourceUploader(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + if (webApplicationContextWrapper == null) { + getLogger().error("Failed to get web application context from context."); + return null; + } + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(IResourceUploader.class); + + } + + + protected DownloadArtifactLogic getLogic(ServletContext context) { + DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR); + + if (downloadLogic == null) { + BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context"); + return null; + } + return downloadLogic; + } + + protected Response buildResponse(int status, String errorMessage) { + + ServletJsonResponse jsonResponse = new ServletJsonResponse(); + jsonResponse.setDescription(errorMessage); + jsonResponse.setSource(Constants.CATALOG_BE); + + Response response = Response.status(status).entity(jsonResponse).build(); + + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java index 3ad15961e7..9829566a12 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java @@ -20,20 +20,12 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -48,77 +40,75 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Types Fetch Servlet", description = "Types Fetch Servlet") @Singleton public class TypesFetchServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(TypesFetchServlet.class.getName()); - - @GET - @Path("dataTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Data types not found") }) - public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Wrapper<Response> responseWrapper = new Wrapper<Response>(); - Wrapper<User> userWrapper = new Wrapper<User>(); - ServletContext context = request.getSession().getServletContext(); - - try { - init(log); - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} | modifier id is {}", url, userId); - - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes(); - - if (allDataTypes.isRight()) { - log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value()); - Response errorResponse = buildErrorResponse(allDataTypes.right().value()); - responseWrapper.setInnerElement(errorResponse); - - // return buildErrorResponse(allDataTypes.right().value()); - } else { - - Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); - String dataTypeJson = gson.toJson(dataTypes); - Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); - responseWrapper.setInnerElement(okResponse); - - } - } - - return responseWrapper.getInnerElement(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get all data types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); - log.debug("get all data types failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - } - - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); - return propertytBl; - } + private static final Logger log = LoggerFactory.getLogger(TypesFetchServlet.class); + + @GET + @Path("dataTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Data types not found") }) + public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Wrapper<Response> responseWrapper = new Wrapper<Response>(); + Wrapper<User> userWrapper = new Wrapper<User>(); + ServletContext context = request.getSession().getServletContext(); + + try { + init(log); + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} | modifier id is {}", url, userId); + + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes(); + + if (allDataTypes.isRight()) { + log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value()); + Response errorResponse = buildErrorResponse(allDataTypes.right().value()); + responseWrapper.setInnerElement(errorResponse); + + } else { + + Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value(); + String dataTypeJson = gson.toJson(dataTypes); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); + responseWrapper.setInnerElement(okResponse); + + } + } + + return responseWrapper.getInnerElement(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); + log.debug("get all data types failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + } + + private PropertyBusinessLogic getPropertyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); + return propertytBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java index bb0be372bf..92f15c4a1d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java @@ -20,27 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; @@ -52,7 +38,6 @@ import org.openecomp.sdc.be.components.impl.PolicyTypeImportManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PolicyTypeDefinition; @@ -63,244 +48,256 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.context.WebApplicationContext; - -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/uploadType") -@Api(value = "Catalog Types Upload", description = "Upload Type from yaml") -@Singleton +@Api(value = "Catalog Types Upload") +@Controller public class TypesUploadServlet extends AbstractValidationsServlet { - @Resource - private CapabilityTypeImportManager capabilityTypeImportManager; - - @Resource - private InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager; - - @Resource - private CategoriesImportManager categoriesImportManager; - - @Resource - private DataTypeImportManager dataTypeImportManager; - - @Resource - private GroupTypeImportManager groupTypeImportManager; - - @Resource - private PolicyTypeImportManager policyTypeImportManager; - - private static Logger log = LoggerFactory.getLogger(TypesUploadServlet.class.getName()); - - @POST - @Path("/capability") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Capability Type already exist") }) - public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - capabilityTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CapabilityTypeImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name()); - } - - @POST - @Path("/interfaceLifecycle") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) - public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - interfaceLifecycleTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> InterfaceLifecycleTypeImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types"); - } - - @POST - @Path("/categories") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Category already exist") }) - public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - categoriesImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CategoriesImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories"); - } - - @POST - @Path("/datatypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Data types already exist") }) - public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - dataTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> DataTypeImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); - } - - @POST - @Path("/grouptypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "group types already exist") }) - public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - groupTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> GroupTypeImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName()); - } - - @POST - @Path("/policytypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "policy types already exist") }) - public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - policyTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> PolicyTypeImportManager.class); - ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createPolicyTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.PolicyType.getName()); - } - - private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { - init(log); - String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); - try { - Wrapper<Response> responseWrapper = new Wrapper<>(); - Wrapper<User> userWrapper = new Wrapper<>(); - Wrapper<String> yamlStringWrapper = new Wrapper<>(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - validateUserRole(responseWrapper, userWrapper.getInnerElement()); - } - - if (responseWrapper.isEmpty()) { - validateDataNotNull(responseWrapper, file); - } - - if (responseWrapper.isEmpty()) { - fillZipContents(yamlStringWrapper, file); - } - - if (responseWrapper.isEmpty()) { - createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement()); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - log.debug("create {} failed with exception:", elementTypeName, e); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) { - Either<T, ResponseFormat> eitherResult = elementsCreater.get(); - if (eitherResult.isRight()) { - Response response = buildErrorResponse(eitherResult.right().value()); - responseWrapper.setInnerElement(response); - } else { - try { - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); - responseWrapper.setInnerElement(response); - } catch (Exception e) { - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(response); - } - } - } - - // data types - private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) { - final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name()); - } - - // group types - private void createGroupTypes(Wrapper<Response> responseWrapper, String groupTypesYml) { - final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); - } - - // policy types - private void createPolicyTypes(Wrapper<Response> responseWrapper, String policyTypesYml) { - final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); - } - - // data types - private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) { - Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get(); - - if (eitherResult.isRight()) { - Response response = buildErrorResponse(eitherResult.right().value()); - responseWrapper.setInnerElement(response); - } else { - Object representation; - try { - List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value(); - ActionStatus status = ActionStatus.OK; - if (list != null) { - - // Group result by the right value - true or false. - // I.e., get the number of data types which are new and - // which are old. - Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight)); - if (collect != null) { - Set<Boolean> keySet = collect.keySet(); - if (keySet.size() == 1) { - Boolean isNew = keySet.iterator().next(); - if (isNew.booleanValue() == true) { - // all data types created at the first time - status = ActionStatus.CREATED; - } else { - // All data types already exists - - status = alreadyExistStatus; - } - } - } - } - representation = RepresentationUtils.toRepresentation(eitherResult.left().value()); - - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation); - responseWrapper.setInnerElement(response); - - } catch (IOException e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); - log.debug("failed to convert {} to json", elementTypeName, e); - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(response); - } - } - } - - private <T> T initElementTypeImportManager(ServletContext context, Supplier<Class<T>> classGetter) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - T elementTypeImortManager = webApplicationContext.getBean(classGetter.get()); - return elementTypeImortManager; - } + private static final Logger log = LoggerFactory.getLogger(TypesUploadServlet.class); + private CapabilityTypeImportManager capabilityTypeImportManager; + + private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager; + + private final CategoriesImportManager categoriesImportManager; + + private final DataTypeImportManager dataTypeImportManager; + + private final GroupTypeImportManager groupTypeImportManager; + + private final PolicyTypeImportManager policyTypeImportManager; + + public TypesUploadServlet(CapabilityTypeImportManager capabilityTypeImportManager, InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager, CategoriesImportManager categoriesImportManager, DataTypeImportManager dataTypeImportManager, GroupTypeImportManager groupTypeImportManager, PolicyTypeImportManager policyTypeImportManager) { + this.capabilityTypeImportManager = capabilityTypeImportManager; + this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager; + this.categoriesImportManager = categoriesImportManager; + this.dataTypeImportManager = dataTypeImportManager; + this.groupTypeImportManager = groupTypeImportManager; + this.policyTypeImportManager = policyTypeImportManager; + } + + @POST + @Path("/capability") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Capability Type already exist") }) + public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name()); + } + + @POST + @Path("/interfaceLifecycle") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) + public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types"); + } + + @POST + @Path("/categories") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Category already exist") }) + public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories"); + } + + @POST + @Path("/datatypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Data types already exist") }) + public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); + } + + @POST + @Path("/grouptypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "group types already exist") }) + public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName()); + } + + @POST + @Path("/policytypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "policy types already exist") }) + public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + return uploadElementTypeServletLogic(this::createPolicyTypes, file, request, creator, NodeTypeEnum.PolicyType.getName()); + } + + private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { + init(log); + String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); + try { + Wrapper<Response> responseWrapper = new Wrapper<>(); + Wrapper<User> userWrapper = new Wrapper<>(); + Wrapper<String> yamlStringWrapper = new Wrapper<>(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + validateUserRole(responseWrapper, userWrapper.getInnerElement()); + } + + if (responseWrapper.isEmpty()) { + validateDataNotNull(responseWrapper, file); + } + + if (responseWrapper.isEmpty()) { + fillZipContents(yamlStringWrapper, file); + } + + if (responseWrapper.isEmpty()) { + createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement()); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + log.debug("create {} failed with exception:", elementTypeName, e); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) { + Either<T, ResponseFormat> eitherResult = elementsCreater.get(); + if (eitherResult.isRight()) { + Response response = buildErrorResponse(eitherResult.right().value()); + responseWrapper.setInnerElement(response); + } else { + try { + Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); + responseWrapper.setInnerElement(response); + } catch (Exception e) { + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(response); + log.error("#createElementsType - json serialization failed with error: ", e); + } + } + } + + // data types + private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) { + final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name()); + } + + // group types + private void createGroupTypes(Wrapper<Response> responseWrapper, String groupTypesYml) { + final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); + } + + // policy types + private void createPolicyTypes(Wrapper<Response> responseWrapper, String policyTypesYml) { + final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); + } + + // data types + private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) { + Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get(); + + if (eitherResult.isRight()) { + Response response = buildErrorResponse(eitherResult.right().value()); + responseWrapper.setInnerElement(response); + } else { + Object representation; + try { + List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value(); + ActionStatus status = ActionStatus.OK; + if (list != null) { + + // Group result by the right value - true or false. + // I.e., get the number of data types which are new and + // which are old. + Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight)); + if (collect != null) { + Set<Boolean> keySet = collect.keySet(); + if (keySet.size() == 1) { + Boolean isNew = keySet.iterator().next(); + if (isNew.booleanValue()) { + // all data types created at the first time + status = ActionStatus.CREATED; + } else { + // All data types already exists + + status = alreadyExistStatus; + } + } + } + } + representation = RepresentationUtils.toRepresentation(eitherResult.left().value()); + + Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation); + responseWrapper.setInnerElement(response); + + } catch (IOException e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); + log.debug("failed to convert {} to json", elementTypeName, e); + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(response); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java index a6f6359ac1..c9ea5dd951 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java @@ -20,10 +20,22 @@ package org.openecomp.sdc.be.servlets; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.List; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.servlet.ServletContext; @@ -40,437 +52,352 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/user") @Api(value = "User Administration", description = "User admininstarator operations") @Singleton public class UserAdminServlet extends BeGenericServlet { - private static final String ROLE_DELIMITER = ","; - private static Logger log = LoggerFactory.getLogger(UserAdminServlet.class.getName()); - - /*************************************** - * API start - *************************************************************/ - - /* User by userId CRUD start */ - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all user details - @GET - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); - - if (either.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } else { - if (either.left().value() != null) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); - log.debug("get user failed with unexpected error: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // update user - internal API - /* - * @POST - * - * @Path("/{userId}") - * - * @Consumes(MediaType.APPLICATION_JSON) - * - * @Produces(MediaType.APPLICATION_JSON) - * - * @ApiOperation(value = "update user - internal API", notes = "Update user", response = User.class) - * - * @ApiResponses(value = { - * - * @ApiResponse(code = 200, message = "Update user OK"), - * - * @ApiResponse(code = 400, message = "Invalid Content."), - * - * @ApiResponse(code = 403, message = "Missing information/Restricted operation"), - * - * @ApiResponse(code = 404, message = "User not found"), - * - * @ApiResponse(code = 405, message = "Method Not Allowed"), - * - * @ApiResponse(code = 409, message = "User already exists"), - * - * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser, - * - * @Context final HttpServletRequest request, - * - * @ApiParam(value="json describe the update user", required=true) String data, - * - * @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { - * - * ServletContext context = request.getSession().getServletContext(); - * - * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); - * - * // get modifier id User modifier = new User(); modifier.setUserId(modifierAttId); log.debug("modifier id is {}", modifierAttId); - * - * Response response = null; - * - * try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either<User, ResponseFormat> - * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser); - * - * if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response = - * buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response; - * - * } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Update User Metadata"); log.debug("Update User Metadata failed with exception", e); response = - * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response; - * - * } } - * - */ - /* User userId CRUD end */ - - /* User role CRUD start */ - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve user role - @GET - @Path("/{userId}/role") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getRole) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); - if (either.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } else { - if (either.left().value() != null) { - String roleJson = ("{ \"role\" : \"" + either.left().value().getRole().toString() + "\" }"); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User Role"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role"); - log.debug("Get user role failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // update user role - @POST - @Path("/{userId}/role") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "update user role", notes = "Update user role", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"), - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request, - @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(modifierUserId); - log.debug("modifier id is {}", modifierUserId); - - Response response = null; - - try { - UserBusinessLogic businessLogic = getUserAdminManager(context); - User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); - Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole()); - - if (updateUserResponse.isRight()) { - log.debug("failed to update user role"); - response = buildErrorResponse(updateUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); - log.debug("Update User Role failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* User role CRUD end */ - - /* New user CRUD start */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - Response response = null; - - try { - UserBusinessLogic businessLogic = getUserAdminManager(context); - User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value(); - Either<User, ResponseFormat> createUserResponse = businessLogic.createUser(modifier, newUserInfo); - - if (createUserResponse.isRight()) { - log.debug("failed to create user"); - response = buildErrorResponse(createUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); - log.debug("Create User failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* New user CRUD end */ - - /* User authorization start */ - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // User Authorization - @GET - @Path("/authorize") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - - @ApiOperation(value = "authorize", notes = "authorize user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName, - @HeaderParam("HTTP_CSP_EMAIL") String email) { - - try { - userId = (userId != null ? URLDecoder.decode(userId, "UTF-8") : null); - firstName = (firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null); - lastName = (lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null); - email = (email != null ? URLDecoder.decode(email, "UTF-8") : null); - } catch (UnsupportedEncodingException e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Authorize User - decode headers"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers"); - ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(errorResponseWrapper); - } - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User authUser = new User(); - authUser.setUserId(userId); - authUser.setFirstName(firstName); - authUser.setLastName(lastName); - authUser.setEmail(email); - log.debug("auth user id is {}", userId); - - Response response = null; - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either<User, ResponseFormat> authorize = userAdminManager.authorize(authUser); - - if (authorize.isRight()) { - log.debug("authorize user failed"); - response = buildErrorResponse(authorize.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - log.debug("authorize user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /* User authorization end */ - - @GET - @Path("/admins") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getAdminsUser(@PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either<List<User>, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext()); - - if (either.isRight()) { - log.debug("Failed to get all admin users"); - return buildErrorResponse(either.right().value()); - } else { - if (either.left().value() != null) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Administrators"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators"); - log.debug("get all admins failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/users") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"), - @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userId); - - List<String> rolesList = new ArrayList<>(); - if (roles != null && !roles.trim().isEmpty()) { - String[] rolesArr = roles.split(ROLE_DELIMITER); - for (String role : rolesArr) { - rolesList.add(role.trim()); - } - } - - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either<List<User>, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles); - - if (either.isRight()) { - log.debug("Failed to get ASDC users"); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); - log.debug("get users failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // delete user - @DELETE - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "delete user", notes = "Delete user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userIdHeader); - - User modifier = new User(); - modifier.setUserId(userIdHeader); - - Response response = null; - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either<User, ResponseFormat> deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId); - - if (deactiveUserResponse.isRight()) { - log.debug("Failed to deactivate user"); - response = buildErrorResponse(deactiveUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); - log.debug("deactivate user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + private static final String ROLE_DELIMITER = ","; + private static final Logger log = LoggerFactory.getLogger(UserAdminServlet.class); + + /*************************************** + * API start + *************************************************************/ + + /* User by userId CRUD start */ + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all user details + @GET + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); + + if (either.isRight()) { + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } else { + if (either.left().value() != null) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); + log.debug("get user failed with unexpected error: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{userId}/role") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getRole) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either<User, ActionStatus> either = userAdminManager.getUser(userId, false); + if (either.isRight()) { + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } else { + if (either.left().value() != null) { + String roleJson = "{ \"role\" : \"" + either.left().value().getRole() + "\" }"; + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role"); + log.debug("Get user role failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // update user role + @POST + @Path("/{userId}/role") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update user role", notes = "Update user role", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"), + @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request, + @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(modifierUserId); + log.debug("modifier id is {}", modifierUserId); + + Response response = null; + + try { + UserBusinessLogic businessLogic = getUserAdminManager(context); + User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); + Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole()); + + if (updateUserResponse.isRight()) { + log.debug("failed to update user role"); + response = buildErrorResponse(updateUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); + log.debug("Update User Role failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + /* User role CRUD end */ + + /* New user CRUD start */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + Response response = null; + + try { + UserBusinessLogic businessLogic = getUserAdminManager(context); + User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value(); + Either<User, ResponseFormat> createUserResponse = businessLogic.createUser(modifier, newUserInfo); + + if (createUserResponse.isRight()) { + log.debug("failed to create user"); + response = buildErrorResponse(createUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); + log.debug("Create User failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + /* New user CRUD end */ + + /* User authorization start */ + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // User Authorization + @GET + @Path("/authorize") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + + @ApiOperation(value = "authorize", notes = "authorize user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName, + @HeaderParam("HTTP_CSP_EMAIL") String email) { + + try { + userId = userId != null ? URLDecoder.decode(userId, "UTF-8") : null; + firstName = firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null; + lastName = lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null; + email = email != null ? URLDecoder.decode(email, "UTF-8") : null; + } catch (UnsupportedEncodingException e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers"); + ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + log.error("#authorize - authorization decoding failed with error: ", e); + return buildErrorResponse(errorResponseWrapper); + } + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User authUser = new User(); + authUser.setUserId(userId); + authUser.setFirstName(firstName); + authUser.setLastName(lastName); + authUser.setEmail(email); + log.debug("auth user id is {}", userId); + + Response response = null; + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either<User, ResponseFormat> authorize = userAdminManager.authorize(authUser); + + if (authorize.isRight()) { + log.debug("authorize user failed"); + response = buildErrorResponse(authorize.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value()); + return response; + + } catch (Exception e) { + log.debug("authorize user failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /* User authorization end */ + + @GET + @Path("/admins") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getAdminsUser(@Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either<List<User>, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext()); + + if (either.isRight()) { + log.debug("Failed to get all admin users"); + return buildErrorResponse(either.right().value()); + } else { + if (either.left().value() != null) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators"); + log.debug("get all admins failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/users") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"), + @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + List<String> rolesList = new ArrayList<>(); + if (roles != null && !roles.trim().isEmpty()) { + String[] rolesArr = roles.split(ROLE_DELIMITER); + for (String role : rolesArr) { + rolesList.add(role.trim()); + } + } + + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either<List<User>, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles); + + if (either.isRight()) { + log.debug("Failed to get ASDC users"); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); + log.debug("get users failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // delete user + @DELETE + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete user", notes = "Delete user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userIdHeader); + + User modifier = new User(); + modifier.setUserId(userIdHeader); + + Response response = null; + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either<User, ResponseFormat> deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId); + + if (deactiveUserResponse.isRight()) { + log.debug("Failed to deactivate user"); + response = buildErrorResponse(deactiveUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); + log.debug("deactivate user failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java index faebb7614b..fb5710cc20 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,19 @@ package org.openecomp.sdc.be.switchover.detector; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import java.net.InetAddress; import java.util.Properties; import java.util.concurrent.ExecutorService; @@ -29,293 +42,272 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.rest.HttpRestClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - @Component("switchover-detector") public class SwitchoverDetector { - protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector"; + protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector"; - private static Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT); + private static final Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT); - private SwitchoverDetectorConfig switchoverDetectorConfig; + private SwitchoverDetectorConfig switchoverDetectorConfig; - private Properties authHeader = null; + private Properties authHeader = null; - private long detectorInterval = 60; + private long detectorInterval = 60; - private int maxBeQueryAttempts = 3; + private int maxBeQueryAttempts = 3; - private int maxFeQueryAttempts = 3; + private int maxFeQueryAttempts = 3; - private Boolean beMatch = null; + private Boolean beMatch = null; - private Boolean feMatch = null; + private Boolean feMatch = null; - private static Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class); - private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); + private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); - private ScheduledFuture<?> scheduledFuture = null; + private ScheduledFuture<?> scheduledFuture = null; - ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Switchover-Detector-Task"); - } - }); + ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "Switchover-Detector-Task"); + } + }); - SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; + SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; - public enum SwitchoverDetectorState { + public enum SwitchoverDetectorState { - UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby"); + UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby"); - private String state; + private String state; - SwitchoverDetectorState(String state) { - this.state = state; - } + SwitchoverDetectorState(String state) { + this.state = state; + } - public String getState() { - return state; - } - } + public String getState() { + return state; + } + } - public enum SwitchoverDetectorGroup { + public enum SwitchoverDetectorGroup { - BE_SET("beSet"), FE_SET("feSet"); + BE_SET("beSet"), FE_SET("feSet"); - private String group; + private String group; - SwitchoverDetectorGroup(String group) { - this.group = group; - } + SwitchoverDetectorGroup(String group) { + this.group = group; + } - public String getGroup() { - return group; - } - } + public String getGroup() { + return group; + } + } - public String getSiteMode() { - return siteMode; - } + public String getSiteMode() { + return siteMode; + } - public void setSiteMode(String mode) { - this.siteMode = mode; - } + public void setSiteMode(String mode) { + this.siteMode = mode; + } - private Boolean queryBe() { - return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts); - } + private Boolean queryBe() { + return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts); + } - private Boolean queryFe() { - return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts); - } + private Boolean queryFe() { + return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts); + } - private void setAuthorizationProperties() { - String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword(); - String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes())); - authHeader = new Properties(); - authHeader.put("Authorization", auth); - } + private void setAuthorizationProperties() { + String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword(); + String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes())); + authHeader = new Properties(); + authHeader.put("Authorization", auth); + } - private void initializeSiteMode() { - while (siteMode == SwitchoverDetectorState.UNKNOWN.getState()) { + private void initializeSiteMode() { + while (siteMode.equals(SwitchoverDetectorState.UNKNOWN.getState())) { - beMatch = queryBe(); - feMatch = queryFe(); + beMatch = queryBe(); + feMatch = queryFe(); - if (beMatch == feMatch && beMatch != null) { - if (beMatch) { - setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); - } else { - setSiteMode(SwitchoverDetectorState.STANDBY.getState()); - } - } - } - } + if (beMatch == feMatch && beMatch != null) { + if (beMatch) { + setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); + } else { + setSiteMode(SwitchoverDetectorState.STANDBY.getState()); + } + } + } + } - private Boolean queryGss(String fqdn, String vip, int maxAttempts) { + private Boolean queryGss(String fqdn, String vip, int maxAttempts) { - Boolean result = null; - int attempts = 0; + Boolean result = null; + int attempts = 0; - while (result == null && (++attempts < maxAttempts)) { - try { - InetAddress inetAddress = InetAddress.getByName(fqdn); - result = inetAddress.getHostAddress().equals(vip); + while (result == null && (++attempts < maxAttempts)) { + try { + InetAddress inetAddress = InetAddress.getByName(fqdn); + result = inetAddress.getHostAddress().equals(vip); - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - logger.debug("Error occured during switchover detector query, Result is {}", message, e); - } - } - if (null == result) { - BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts"); - } - return result; - } - - public class SwitchoverDetectorScheduledTask implements Runnable { - - public SwitchoverDetectorScheduledTask() { - - } - - @Override - public void run() { - logger.trace("Executing Switchover Detector Task - Start"); - - initializeSiteMode(); - - Boolean beRes = queryBe(); - Boolean feRes = queryFe(); - - if (null == beRes || null == feRes) { - return; - } - - Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) & (beMatch != beRes || feMatch != feRes); - - updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired); - - beMatch = beRes; - feMatch = feRes; - } - - ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Switchover-Detector-Thread"); - } - }); - - private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) { - if (bothMatch && previousModeStandby) { - logger.trace("Site switch over was done. Site is now in active mode"); - setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); - BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); - } else if (!bothMatch && !previousModeStandby) { - logger.trace("Site switch over was done. Site is now in stand-by mode"); - setSiteMode(SwitchoverDetectorState.STANDBY.getState()); - BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); - } - if (updateRequired) { - changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup()); - changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup()); - publishNetwork(); - } - } - - private void changeSitePriority(String groupToSet) { - - String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl(); - String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody(); - - HttpRestClient httpRestClient = new HttpRestClient(); - - try { - httpRestClient.doPUT(url, authHeader, body); - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - - logger.debug("Error occured during change site priority request, Result is {}", message, e); - } - - } - - private void publishNetwork() { - - String url = switchoverDetectorConfig.getPublishNetworkUrl(); - String body = switchoverDetectorConfig.getPublishNetworkBody(); - - HttpRestClient httpRestClient = new HttpRestClient(); - - try { - httpRestClient.doPOST(url, authHeader, body); - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - - logger.debug("Error occured during publish network request, Result is {}", message, e); - } - } - - } - - @PostConstruct - private void init() { - logger.info("Enter init method of SwitchoverDetector"); - - switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector(); - - if (!switchoverDetectorConfig.getEnabled()) { - logger.info("switchover detector service is disabled"); - return; - } - - Long detectorIntervalConfig = switchoverDetectorConfig.getInterval(); - if (detectorIntervalConfig != null) { - detectorInterval = detectorIntervalConfig.longValue(); - } - - Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); - if (maxAttempts != null) { - maxBeQueryAttempts = maxAttempts.intValue(); - } - maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); - if (maxAttempts != null) { - maxFeQueryAttempts = maxAttempts.intValue(); - } - - setAuthorizationProperties(); - logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval); - - this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask(); - startSwitchoverDetectorTask(); - logger.trace("Exit init method of SwitchoverDetector"); - - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (switchoverDetectorScheduler != null) { - switchoverDetectorScheduler.shutdown(); - } - - } - - public void startSwitchoverDetectorTask() { - if (this.scheduledFuture == null) { - this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS); - } - } + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during switchover detector query, Result is {}", message, e); + } + } + if (null == result) { + BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts"); + } + return result; + } + + public class SwitchoverDetectorScheduledTask implements Runnable { + + public SwitchoverDetectorScheduledTask() { + + } + + @Override + public void run() { + logger.trace("Executing Switchover Detector Task - Start"); + + initializeSiteMode(); + + Boolean beRes = queryBe(); + Boolean feRes = queryFe(); + + if (null == beRes || null == feRes) { + return; + } + + Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) && (beMatch != beRes || feMatch != feRes); + + updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired); + + beMatch = beRes; + feMatch = feRes; + } + + ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "Switchover-Detector-Thread"); + } + }); + + private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) { + if (bothMatch && previousModeStandby) { + logger.trace("Site switch over was done. Site is now in active mode"); + setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); + BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); + } else if (!bothMatch && !previousModeStandby) { + logger.trace("Site switch over was done. Site is now in stand-by mode"); + setSiteMode(SwitchoverDetectorState.STANDBY.getState()); + BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); + } + if (updateRequired) { + changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup()); + changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup()); + publishNetwork(); + } + } + + private void changeSitePriority(String groupToSet) { + + String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl(); + String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody(); + + try { + HttpRequest.put(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON)); + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during change site priority request, Result is {}", message, e); + } + + } + + private void publishNetwork() { + + String url = switchoverDetectorConfig.getPublishNetworkUrl(); + String body = switchoverDetectorConfig.getPublishNetworkBody(); + try { + HttpRequest.post(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON)); + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during publish network request, Result is {}", message, e); + } + } + + } + + @PostConstruct + private void init() { + logger.info("Enter init method of SwitchoverDetector"); + + switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector(); + + if (!switchoverDetectorConfig.getEnabled()) { + logger.info("switchover detector service is disabled"); + return; + } + + Long detectorIntervalConfig = switchoverDetectorConfig.getInterval(); + if (detectorIntervalConfig != null) { + detectorInterval = detectorIntervalConfig.longValue(); + } + + Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); + if (maxAttempts != null) { + maxBeQueryAttempts = maxAttempts.intValue(); + } + maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); + if (maxAttempts != null) { + maxFeQueryAttempts = maxAttempts.intValue(); + } + + setAuthorizationProperties(); + logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval); + + this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask(); + startSwitchoverDetectorTask(); + logger.trace("Exit init method of SwitchoverDetector"); + + } + + @PreDestroy + private void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (switchoverDetectorScheduler != null) { + switchoverDetectorScheduler.shutdown(); + } + + } + + public void startSwitchoverDetectorTask() { + if (this.scheduledFuture == null) { + this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java index 13356e5de4..f13331ed0b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java @@ -20,19 +20,19 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.openecomp.sdc.generator.data.ArtifactType; +import java.util.List; + public class ArtifactTypes { - private List<ArtifactType> artifactTypes; + private List<ArtifactType> artifactTypes; - public List<ArtifactType> getArtifactTypes() { - return artifactTypes; - } + public List<ArtifactType> getArtifactTypes() { + return artifactTypes; + } - public void setArtifactTypes(List<ArtifactType> artifactTypes) { - this.artifactTypes = artifactTypes; - } + public void setArtifactTypes(List<ArtifactType> artifactTypes) { + this.artifactTypes = artifactTypes; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java deleted file mode 100644 index 7fecced358..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.tosca; - -import org.openecomp.sdc.be.model.Component; - -public class CSARTool { - public static byte[] createCsar(Component component) { - - final String TOSCA_META_VERSION = "1.0"; - final String CSAR_VERSION = component.getCsarVersion(); - final String CREATED_BY = component.getCreatorFullName(); - final String ENTRY_DEFINITIONS = component.getNormalizedName(); - - /* - * StringBuilder builder = new StringBuilder(); try( FileOutputStream f = new FileOutputStream("test.zip"); ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); ){ } - */ - - return null; - } - - public static String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s"; - - return null; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java index 886b654b81..4dbbf925d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java @@ -20,50 +20,34 @@ package org.openecomp.sdc.be.tosca; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.tosca.ToscaUtils.SubstituitionEntry; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; +import org.openecomp.sdc.be.tosca.model.*; import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.*; -import fj.data.Either; /** * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template * @@ -71,502 +55,545 @@ import fj.data.Either; @org.springframework.stereotype.Component("capabilty-requirement-convertor") @Scope(value = "singleton") public class CapabiltyRequirementConvertor { - - private static final String NO_CAPABILITIES = "No Capabilities for node type"; - private static CapabiltyRequirementConvertor instance; - private static Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class.getName()); - public static final String PATH_DELIMITER = "."; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - - protected CapabiltyRequirementConvertor() {} - - public static synchronized CapabiltyRequirementConvertor getInstance() { - if (instance == null) { - instance = new CapabiltyRequirementConvertor(); - } - return instance; - } - /** - * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template - * @param componentInstance - * @param dataTypes - * @param nodeTemplate - * @return - */ - public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) { - - Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities(); - if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { - Map<String, ToscaTemplateCapability> capabilties = new HashMap<>(); - capabilitiesInst.entrySet().forEach(e -> { - List<CapabilityDefinition> capList = e.getValue(); - if (capList != null && !capList.isEmpty()) { - capList.forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilties, c)); - } - }); - if (MapUtils.isNotEmpty(capabilties)) { - nodeTemplate.setCapabilities(capabilties); - } - } - return Either.left(nodeTemplate); - } - - private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c) { - if (CollectionUtils.isNotEmpty(c.getProperties())) { - c.getProperties() - .stream() - .filter(p -> p.getValue() != null || p.getDefaultValue() != null) - .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties, c, p)); - } - } - - private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c, ComponentInstanceProperty p) { - if (logger.isDebugEnabled()) { - logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), c.getName(), p.getValue()); - } - ToscaTemplateCapability toscaTemplateCapability = capabilties.get(c.getName()); - if (toscaTemplateCapability == null) { - toscaTemplateCapability = new ToscaTemplateCapability(); - capabilties.put(c.getName(), toscaTemplateCapability); - } - Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties(); - if (toscaCapProp == null) { - toscaCapProp = new HashMap<>(); - } - Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); - toscaCapProp.put(p.getName(), convertedValue); - toscaTemplateCapability.setProperties(toscaCapProp); - } - - private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { - logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); - String propertyType = prop.getType(); - String innerType = null; - if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { - innerType = prop.getSchema().getProperty().getType(); - } - String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); - return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); - } - /** - * Allows to convert requirements of a node type to tosca template requirements representation - * @param component - * @param nodeType - * @return - */ - public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) { - List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component); - if (!toscaRequirements.isEmpty()) { - nodeType.setRequirements(toscaRequirements); - } - logger.debug("Finish convert Requirements for node type"); - - return Either.left(nodeType); - } - - /** - * Allows to convert component requirements to the tosca template substitution mappings requirements - * @param componentsCache - * @param component - * @param substitutionMappings - * @return - */ - public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) { - Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); - Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); - if(toscaRequirementsRes.isRight()){ - result = Either.right(toscaRequirementsRes.right().value()); - logger.error("Failed convert requirements for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { - substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); - result = Either.left(substitutionMappings); - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - return result; - } - - private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) { - Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); - List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>(); - if (requirements != null) { - for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { - entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { - ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); - Map<String, ToscaRequirement> requirement = new HashMap<>(); - - requirement.put(pair.left, pair.right); - toscaRequirements.add(requirement); - }); - logger.debug("Finish convert Requirements for node type"); - } - } else { - logger.debug("No Requirements for node type"); - } - return toscaRequirements; - } - - private boolean filter(Component component, String ownerId) { - return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); - } - - private boolean isNodeTypeOwner(Component component, String ownerId) { - return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); - } - - private String getSubPathByLastDelimiterAppearance(String path) { - return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); - } - - private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) { - Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); - Either<Map<String, String[]>, ToscaError> result; - if (requirements != null) { - result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); - } else { - result = Either.left(Maps.newHashMap()); - logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); - } - return result; - } - - private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) { - - Map<String, String[]> toscaRequirements = new HashMap<>(); - Either<Map<String, String[]>, ToscaError> result = null; - for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { - Optional<RequirementDefinition> failedToAddRequirement = entry.getValue() - .stream() - .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) { - - Map<String, String[]> toscaRequirements = new HashMap<>(); - Either<Map<String, String[]>, ToscaError> result = null; - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue() - .stream() - .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); - } - logger.debug("Finish convert capalilities for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, List<String> path){ - - SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); - - if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, entry)){ - return false; - } - logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); - if (entry.getSourceName() != null) { - addEntry(capReqMap, component, path, entry); - } - logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); - return true; - - } - - private boolean shouldBuildSubstitutionName(Component component, List<String> path) { - return !ToscaUtils.isComplexVfc(component) && CollectionUtils.isNotEmpty(path) && path.iterator().hasNext(); - } - - private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, SubstituitionEntry entry) { - Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); - if(ci.isPresent()){ - Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ci.get()); - if(buildSubstitutedName.isRight()){ - return false; - } - entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); - entry.setSourceName(buildSubstitutedName.left().value()); - } else { - return false; - } - return true; - } - - private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) { - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); - if (findFirst.isPresent()) { - entry.setOwner(findFirst.get().getNormalizedName()); - } - toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); - } - - private Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, ComponentInstance instance) { - - Either<String, Boolean> result = null; - Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance); - if(getOriginRes.isRight()){ - logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); - result = Either.right(false); - } - if(result == null){ - List<String> reducedPath = getReducedPath(path); - reducedPath.remove(reducedPath.size()-1); - result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); - } - return result; - } - - private String getRequirementPath(Component component, RequirementDefinition r) { - - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List<String> capPath = r.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); - } - } - return ""; - } - - private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { - String name = r.getName(); - if (!isNodeType) { - name = getRequirementPath(component, r); - } - logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); - ToscaRequirement toscaRequirement = new ToscaRequirement(); - - List<Object> occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(r.getMinOccurrences())); - if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - occurences.add(r.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(r.getMaxOccurrences())); - } - toscaRequirement.setOccurrences(occurences); - toscaRequirement.setNode(r.getNode()); - toscaRequirement.setCapability(r.getCapability()); - toscaRequirement.setRelationship(r.getRelationship()); - - return new ImmutablePair<>(name, toscaRequirement); - } - - /** - * Allows to convert capabilities of a node type to tosca template capabilities - * @param component - * @param dataTypes - * @return - */ - public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) { - Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); - Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert capabilities of a server proxy node type to tosca template capabilities - * @param component - * @param proxyComponent - * @param instanceProxy - * @param dataTypes - * @return - */ - public Map<String, ToscaCapability> convertProxyCapabilities(Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) { - Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities(); - Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert component capabilities to the tosca template substitution mappings capabilities - * @param componentsCache - * @param component - * @return - */ - public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) { - Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); - Either<Map<String, String[]>, ToscaError> res; - if (capabilities != null) { - res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); - } else { - res = Either.left(Maps.newHashMap()); - logger.debug(NO_CAPABILITIES); - } - return res; - } - - private String getCapabilityPath(CapabilityDefinition c, Component component) { - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List<String> capPath = c.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); - } - } - return ""; - } - - private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes) { - String name = c.getName(); - if (!isNodeType) { - name = getCapabilityPath(c, component); - } - logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); - ToscaCapability toscaCapability = new ToscaCapability(); - toscaCapability.setDescription(c.getDescription()); - toscaCapability.setType(c.getType()); - - List<Object> occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(c.getMinOccurrences())); - if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - occurences.add(c.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(c.getMaxOccurrences())); - } - toscaCapability.setOccurrences(occurences); - - toscaCapability.setValid_source_types(c.getValidSourceTypes()); - List<ComponentInstanceProperty> properties = c.getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Map<String, ToscaProperty> toscaProperties = new HashMap<>(); - for (PropertyDefinition property : properties) { - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); - toscaProperties.put(property.getName(), toscaProperty); - } - toscaCapability.setProperties(toscaProperties); - } - toscaCapabilities.put(name, toscaCapability); - } - /** - * Allows to build substituted name of capability\requirement of the origin component instance according to the path - * @param componentsCache - * @param originComponent - * @param path - * @param name - * @return - */ - public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) { - StringBuilder substitutedName = new StringBuilder(); - boolean nameBuiltSuccessfully = true; - Either<String, Boolean> result; - if(CollectionUtils.isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ - List<String> reducedPath = getReducedPath(path); - Collections.reverse(reducedPath); - nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); - } - if(nameBuiltSuccessfully){ - result = Either.left(substitutedName.append(name).toString()); - } else { - result = Either.right(nameBuiltSuccessfully); - } - return result; - } - - private List<String> getReducedPath(List<String> path) { - List<String> pathCopy = Lists.newArrayList(); - path.stream().forEach(id -> {if(!pathCopy.contains(id))pathCopy.add(id);}); - return pathCopy; - } - - private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) { - if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ - String instanceId = instanceIdIter.next(); - Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instanceOpt.isPresent()){ - logger.debug("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); - return false; - } - substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); - Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); - if(getOriginRes.isRight()){ - return false; - } - appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); - } - return true; - } - - Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) { - Either<Component, Boolean> result; - Either<Component, StorageOperationStatus> getOriginRes; - if(componentsCache.containsKey(instance.getActualComponentUid())){ - result = Either.left(componentsCache.get(instance.getActualComponentUid())); - } else { - ComponentParametersView filter = getFilter(instance); - getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); - if(getOriginRes.isRight()){ - logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); - result = Either.right(false); - } else { - result = Either.left(getOriginRes.left().value()); - componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); - } - } - return result; - } - - private ComponentParametersView getFilter(ComponentInstance instance) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - if(instance.getIsProxy()){ - filter.setIgnoreCapabilities(false); - filter.setIgnoreRequirements(false); - } - return filter; - } - -} + + private static final String NO_CAPABILITIES = "No Capabilities for node type"; + private static CapabiltyRequirementConvertor instance; + private static final Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class); + public static final String PATH_DELIMITER = "."; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + protected CapabiltyRequirementConvertor() {} + + public static synchronized CapabiltyRequirementConvertor getInstance() { + if (instance == null) { + instance = new CapabiltyRequirementConvertor(); + } + return instance; + } + + public String buildCapabilityNameForComponentInstance( Map<String,Component> componentCache , ComponentInstance componentInstance, CapabilityDefinition c) { + + Either eitherName = buildSubstitutedName(componentCache, c.getName(), c.getPath(), c.getOwnerId(), componentInstance); + + return eitherName.isLeft() ? (String) eitherName.left().value() : c.getName() ; + } + + + /** + * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template + * @param componentInstance + * @param dataTypes + * @param nodeTemplate + * @return + */ + public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) { + + Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities(); + Map<String,Component> componentCache = new HashMap<>(); + if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { + Map<String, ToscaTemplateCapability> capabilities = new HashMap<>(); + capabilitiesInst.entrySet().forEach( e -> { + List<CapabilityDefinition> capList = e.getValue(); + if ( capList != null && !capList.isEmpty() ) { + capList.forEach( c -> { + String capName = buildCapabilityNameForComponentInstance( componentCache , componentInstance , c ) ; + convertOverridenProperties( componentInstance, dataTypes, capabilities, c , capName ); + } ); + } + }); + if (MapUtils.isNotEmpty(capabilities)) { + nodeTemplate.setCapabilities(capabilities); + } + } + return Either.left(nodeTemplate); + } + + private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) { + if (isNotEmpty(c.getProperties())) { + c.getProperties() + .stream() + .filter(p -> p.getValue() != null || p.getDefaultValue() != null) + .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName)); + } + } + + private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p ,String capabilityName) { + if (logger.isDebugEnabled()) { + logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), capabilityName, p.getValue()); + } + ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() ); + + Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties(); + if (toscaCapProp == null) { + toscaCapProp = new HashMap<>(); + } + Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); + toscaCapProp.put(p.getName(), convertedValue); + toscaTemplateCapability.setProperties(toscaCapProp); + } + + private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { + logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); + String propertyType = prop.getType(); + String innerType = null; + if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { + innerType = prop.getSchema().getProperty().getType(); + } + String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); + return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); + } + /** + * Allows to convert requirements of a node type to tosca template requirements representation + * @param component + * @param nodeType + * @return + */ + public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) { + List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component); + if (!toscaRequirements.isEmpty()) { + nodeType.setRequirements(toscaRequirements); + } + logger.debug("Finish convert Requirements for node type"); + + return Either.left(nodeType); + } + + /** + * Allows to convert component requirements to the tosca template substitution mappings requirements + * @param componentsCache + * @param component + * @param substitutionMappings + * @return + */ + public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) { + Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); + Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); + if(toscaRequirementsRes.isRight()){ + result = Either.right(toscaRequirementsRes.right().value()); + logger.error("Failed convert requirements for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { + substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); + result = Either.left(substitutionMappings); + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + return result; + } + + private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) { + Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); + List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>(); + if (requirements != null) { + for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { + entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { + ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); + Map<String, ToscaRequirement> requirement = new HashMap<>(); + + requirement.put(pair.left, pair.right); + toscaRequirements.add(requirement); + }); + logger.debug("Finish convert Requirements for node type"); + } + } else { + logger.debug("No Requirements for node type"); + } + return toscaRequirements; + } + + private boolean filter(Component component, String ownerId) { + return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); + } + + private boolean isNodeTypeOwner(Component component, String ownerId) { + return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); + } + + private String getSubPathByLastDelimiterAppearance(String path) { + return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); + } + + private String dropLast( String path, String delimiter ) { + if (isBlank(path) || isBlank(delimiter)){ + return path; + } + return path.substring(0, path.lastIndexOf(delimiter)); + } + + private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) { + Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); + Either<Map<String, String[]>, ToscaError> result; + if (requirements != null) { + result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); + } else { + result = Either.left(Maps.newHashMap()); + logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); + } + return result; + } + + private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) { + + Map<String, String[]> toscaRequirements = new HashMap<>(); + Either<Map<String, String[]>, ToscaError> result = null; + for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { + Optional<RequirementDefinition> failedToAddRequirement = entry.getValue() + .stream() + .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getOwnerId(), r.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) { + + Map<String, String[]> toscaRequirements = new HashMap<>(); + Either<Map<String, String[]>, ToscaError> result = null; + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue() + .stream() + .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getOwnerId(), c.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); + } + logger.debug("Finish convert capalilities for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, String ownerId, List<String> path){ + + SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); + + if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, ownerId, entry)){ + return false; + } + logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); + if (entry.getSourceName() != null) { + addEntry(capReqMap, component, path, entry); + } + logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); + return true; + + } + + private boolean shouldBuildSubstitutionName(Component component, List<String> path) { + return !ToscaUtils.isComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext(); + } + + private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, String ownerId, SubstituitionEntry entry) { + Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + if(!ci.isPresent()){ + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + + Collections.reverse(path); + + logger.error("try to reverse path {} component {}", path, component.getUniqueId()); + ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + } + if(ci.isPresent()){ + Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ownerId, ci.get()); + if(buildSubstitutedName.isRight()){ + logger.error("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId()); + return false; + } + entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); + entry.setSourceName(buildSubstitutedName.left().value()); + } else { + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + return false; + } + return true; + } + + private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) { + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); + if (findFirst.isPresent()) { + entry.setOwner(findFirst.get().getNormalizedName()); + } + toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); + } + + public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, String ownerId, ComponentInstance instance) { + + Either<String, Boolean> result = null; + Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance); + if(getOriginRes.isRight()){ + logger.error("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); + result = Either.right(false); + } + if(result == null){ + List<String> reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ; + logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath); + reducedPath.remove(reducedPath.size()-1); + result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); + } + return result; + } + + private String getRequirementPath(Component component, RequirementDefinition r) { + + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List<String> capPath = r.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); + } + } + return ""; + } + + private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { + String name = r.getName(); + if (!isNodeType) { + name = getRequirementPath(component, r); + } + logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); + ToscaRequirement toscaRequirement = new ToscaRequirement(); + + List<Object> occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(r.getMinOccurrences())); + if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + occurences.add(r.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(r.getMaxOccurrences())); + } + toscaRequirement.setOccurrences(occurences); + toscaRequirement.setNode(r.getNode()); + toscaRequirement.setCapability(r.getCapability()); + toscaRequirement.setRelationship(r.getRelationship()); + + return new ImmutablePair<>(name, toscaRequirement); + } + + /** + * Allows to convert capabilities of a node type to tosca template capabilities + * @param component + * @param dataTypes + * @return + */ + public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) { + Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); + Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes , c.getName())); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert capabilities of a server proxy node type to tosca template capabilities + * @param component + * @param proxyComponent + * @param instanceProxy + * @param dataTypes + * @return + */ + public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache, Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) { + Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities(); + Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes , buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c ))); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert component capabilities to the tosca template substitution mappings capabilities + * @param componentsCache + * @param component + * @return + */ + public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) { + Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); + Either<Map<String, String[]>, ToscaError> res; + if (capabilities != null) { + res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); + } else { + res = Either.left(Maps.newHashMap()); + logger.debug(NO_CAPABILITIES); + } + return res; + } + + private String getCapabilityPath(CapabilityDefinition c, Component component) { + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List<String> capPath = c.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); + } + } + return ""; + } + + private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes , String capabilityName) { + String name = isNoneBlank(capabilityName) ? capabilityName : c.getName(); + if (!isNodeType) { + name = getCapabilityPath(c, component); + } + logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); + ToscaCapability toscaCapability = new ToscaCapability(); + toscaCapability.setDescription(c.getDescription()); + toscaCapability.setType(c.getType()); + + List<Object> occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(c.getMinOccurrences())); + if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + occurences.add(c.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(c.getMaxOccurrences())); + } + toscaCapability.setOccurrences(occurences); + + toscaCapability.setValid_source_types(c.getValidSourceTypes()); + List<ComponentInstanceProperty> properties = c.getProperties(); + if (isNotEmpty(properties)) { + Map<String, ToscaProperty> toscaProperties = new HashMap<>(); + for (PropertyDefinition property : properties) { + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + toscaProperties.put(property.getName(), toscaProperty); + } + toscaCapability.setProperties(toscaProperties); + } + toscaCapabilities.put(name, toscaCapability); + } + /** + * Allows to build substituted name of capability\requirement of the origin component instance according to the path + * @param componentsCache + * @param originComponent + * @param path + * @param name + * @return + */ + public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) { + StringBuilder substitutedName = new StringBuilder(); + boolean nameBuiltSuccessfully = true; + Either<String, Boolean> result; + if(isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ + List<String> reducedPath = getReducedPath(path); + Collections.reverse(reducedPath); + nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); + } + if(nameBuiltSuccessfully){ + result = Either.left(substitutedName.append(name).toString()); + } else { + result = Either.right(nameBuiltSuccessfully); + } + return result; + } + + protected List<String> getReducedPathByOwner(List<String> path , String ownerId) { + logger.debug("ownerId {}, path {} ", ownerId, path); + if ( CollectionUtils.isEmpty(path) ){ + logger.debug("cannot perform reduce by owner, path to component is empty"); + return path; + } + if ( isBlank(ownerId) ){ + logger.debug("cannot perform reduce by owner, component owner is empty"); + return path; + } + //reduce by owner + Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) -> a.endsWith(ownerId) ? a : b )); + //reduce list&duplicates and preserve order + return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList()); + } + + private List<String> getReducedPath(List<String> path) { + return path.stream().distinct().collect(Collectors.toList()); + } + + private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) { + if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ + String instanceId = instanceIdIter.next(); + Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instanceOpt.isPresent()){ + logger.error("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); + return false; + } + substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); + Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); + if(getOriginRes.isRight()){ + return false; + } + appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); + } + return true; + } + + Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) { + Either<Component, Boolean> result; + Either<Component, StorageOperationStatus> getOriginRes; + if(componentsCache.containsKey(instance.getActualComponentUid())){ + result = Either.left(componentsCache.get(instance.getActualComponentUid())); + } else { + ComponentParametersView filter = getFilter(instance); + getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); + if(getOriginRes.isRight()){ + logger.error("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); + result = Either.right(false); + } else { + result = Either.left(getOriginRes.left().value()); + componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); + } + } + return result; + } + + private ComponentParametersView getFilter(ComponentInstance instance) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + if(instance.getIsProxy()){ + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreCategories(false); + } + return filter; + } + +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index f6ae79b26a..ed3a2462bd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -103,1458 +103,1466 @@ import fj.data.Either; */ @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { - private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName()); - - @Autowired - private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - @Autowired - private ComponentsUtils componentsUtils; - @Autowired - private ToscaExportHandler toscaExportUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - private Gson gson = new Gson(); - - public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); - - public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); - public static final String ARTIFACTS_PATH = "Artifacts/"; - public static final String RESOURCES_PATH = "Resources/"; - public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; - public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; - - public static final String DEFINITIONS_PATH = "Definitions/"; - private static final String CSAR_META_VERSION = "1.0"; - private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; - private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; - private static final String TOSCA_META_VERSION = "1.0"; - private static final String CSAR_VERSION = "1.1"; - public static final String ARTIFACTS = "Artifacts"; - public static final String DEFINITION = "Definitions"; - public static final String DEL_PATTERN = "([/\\\\]+)"; - private static String versionFirstThreeOctates; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + - ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)"; - - public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ - // Artifact Group (i.e Deployment/Informational) - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Type - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Any File Name - ".+"; - public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + @Autowired + private ComponentsUtils componentsUtils; + @Autowired + private ToscaExportHandler toscaExportUtils; + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + private Gson gson = new Gson(); + + public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); + + public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String RESOURCES_PATH = "Resources/"; + public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; + public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; + + public static final String DEFINITIONS_PATH = "Definitions/"; + private static final String CSAR_META_VERSION = "1.0"; + private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; + private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; + private static final String TOSCA_META_VERSION = "1.0"; + private static final String CSAR_VERSION = "1.1"; + public static final String ARTIFACTS = "Artifacts"; + public static final String DEFINITION = "Definitions"; + public static final String DEL_PATTERN = "([/\\\\]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)"; + + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ + // Artifact Group (i.e Deployment/Informational) + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Type + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Any File Name + ".+"; + public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+ // Service Template File Name "([\\w\\_\\-\\.\\s]+)"; public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; - public CsarUtils() { - if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - versionFirstThreeOctates = matcher.group(0); - } else { - versionFirstThreeOctates = ""; - } - } - - /** - * - * @param component - * @param getFromCS - * @param isInCertificationRequest - * @return - */ - public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { - return createCsar(component, getFromCS, isInCertificationRequest, false); - } - - private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - final String createdBy = component.getCreatorFullName(); - - String fileName; - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - fileName = artifactDefinition.getArtifactName(); - - String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); - byte[] csarBlock0Byte = csarBlock0.getBytes(); - - final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); - byte[] toscaBlock0Byte = toscaBlock0.getBytes(); - - Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); - - if (generateCsarZipResponse.isRight()) { - return Either.right(generateCsarZipResponse.right().value()); - } - - return Either.left(generateCsarZipResponse.left().value()); - } - - private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - try ( - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(out); - ){ - zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); - zip.write(csarBlock0Byte); - zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); - zip.write(toscaBlock0Byte); - Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); - if (populateZip.isRight()) { - log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); - return Either.right(populateZip.right().value()); - } - - zip.finish(); - byte[] byteArray = out.toByteArray(); - - return Either.left(byteArray); - } catch (IOException e) { - log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { - - LifecycleStateEnum lifecycleState = component.getLifecycleState(); - String componentYaml; - Either<ToscaRepresentation, ToscaError> exportComponent; - byte[] mainYaml; - // <file name, cassandraId, component> - List<Triple<String, String, Component>> dependencies = null; - List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - String fileName = artifactDefinition.getArtifactName(); - - if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - String cassandraId = artifactDefinition.getEsId(); - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { + public CsarUtils() { + if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + + /** + * + * @param component + * @param getFromCS + * @param isInCertificationRequest + * @return + */ + public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { + return createCsar(component, getFromCS, isInCertificationRequest, false); + } + + private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + final String createdBy = component.getCreatorFullName(); + + String fileName; + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + fileName = artifactDefinition.getArtifactName(); + + String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); + byte[] csarBlock0Byte = csarBlock0.getBytes(); + + final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); + byte[] toscaBlock0Byte = toscaBlock0.getBytes(); + + Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); + + if (generateCsarZipResponse.isRight()) { + return Either.right(generateCsarZipResponse.right().value()); + } + + return Either.left(generateCsarZipResponse.left().value()); + } + + private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + try ( + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(out); + ){ + zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); + zip.write(csarBlock0Byte); + zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); + zip.write(toscaBlock0Byte); + Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); + if (populateZip.isRight()) { + log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); + return Either.right(populateZip.right().value()); + } + + zip.finish(); + byte[] byteArray = out.toByteArray(); + + return Either.left(byteArray); + } catch (IOException e) { + log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { + + LifecycleStateEnum lifecycleState = component.getLifecycleState(); + String componentYaml; + Either<ToscaRepresentation, ToscaError> exportComponent; + byte[] mainYaml; + // <file name, cassandraId, component> + List<Triple<String, String, Component>> dependencies = null; + List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + String fileName = artifactDefinition.getArtifactName(); + + if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + String cassandraId = artifactDefinition.getEsId(); + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); - return Either.right(responseFormat); - } - mainYaml = fromCassandra.left().value(); - - } else { - exportComponent = toscaExportUtils.exportComponent(component); - if (exportComponent.isRight()) { - log.debug("exportComponent failed", exportComponent.right().value()); - ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); - return Either.right(responseFormat); - } - ToscaRepresentation exportResult = exportComponent.left().value(); - componentYaml = exportResult.getMainYaml(); - mainYaml = componentYaml.getBytes(); - dependencies = exportResult.getDependencies(); - } - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(mainYaml); - //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)){ - log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - writeComponentInterface(component, zip, fileName); - } - - generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); - - if (dependencies == null) { - Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); - if (dependenciesRes.isRight()) { - log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), - dependenciesRes.right().value()); - ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); - return Either.right(responseFormat); - } - dependencies = dependenciesRes.left().value().getDependencies(); - } - - //UID <cassandraId,filename,component> - Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>(); - - if (dependencies != null && !dependencies.isEmpty()) { - for (Triple<String, String, Component> d : dependencies) { - String cassandraId = d.getMiddle(); - Component childComponent = d.getRight(); - Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); - - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - return Either.right(responseFormat); - } - - //fill innerComponentsCache - fileName = d.getLeft(); - addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); - addInnerComponentsToCache(innerComponentsCache, childComponent); - - byte[] content = entryData.left().value(); - generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); - } - - //add inner components to CSAR - for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) { - - ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); - - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - // add component to zip - Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), - entryData.right().value()); - return Either.right(responseFormat); - } - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - // add component interface to zip - if (!ModelConverter.isAtomicComponent(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - } - } - - //retrieve SDC.zip from Cassandra - Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); - - if(latestSchemaFilesFromCassandra.isRight()){ - log.error("Error retrieving SDC Schema files from cassandra" ); - return Either.right(latestSchemaFilesFromCassandra.right().value()); - } - - //add files from retireved SDC.zip to Definitions folder in CSAR - Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - - if(addSchemaFilesFromCassandra.isRight()){ - return addSchemaFilesFromCassandra; - } - - // Artifact Generation - if (component.getComponentType() == ComponentTypeEnum.SERVICE - && isInCertificationRequest) { - - List<ArtifactDefinition> aiiArtifactList; - - Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); - - if (handleAAIArtifacts.isLeft()) { - aiiArtifactList = handleAAIArtifacts.left().value(); - } else { - log.debug("AAI Artifacts handling failed"); - return Either.right(handleAAIArtifacts.right().value()); - } - - if (isInCertificationRequest) { - Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( - component, aiiArtifactList, false, true); - - if (handleAllAAIArtifactsInDataModel.isRight()) { - log.debug("AAI Artifacts handling (create, update, delete) failed"); - return Either.right(handleAllAAIArtifactsInDataModel.right().value()); - } - } - - } - - Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - - if (collectedComponentCsarDefinition.isRight()) { - return Either.right(collectedComponentCsarDefinition.right().value()); - } - - return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); - } - - private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - - final int initSize = 2048; - - log.debug("Starting copy from Schema file zip to CSAR zip"); - - try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - - ZipEntry entry = null; - - while ((entry = zipStream.getNextEntry()) != null) { - - String entryName = entry.getName(); - int readSize = initSize; - byte[] entryData = new byte[initSize]; - - while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { - bos.write(entryData, 0, readSize); - } - - bos.flush(); - out.flush(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); - zip.write(out.toByteArray()); - zip.flush(); - out.reset(); - } - } catch (IOException e) { - log.error("Error while writing the SDC schema file to the CSAR {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - log.debug("Finished coppy from Schema file zip to CSAR zip"); - - return Either.left(zip); - } - - - private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - Component childComponent) { - - List<ComponentInstance> instances = childComponent.getComponentInstances(); - - if(instances != null) { - instances.forEach(ci -> { - ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); - if (componentRecord == null) { - // all resource must be only once! - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component componentRI = resource.left().value(); - - Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - if (childArtifactDefinition != null) { - //add to cache - addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); - } - - //if not atomic - insert inner components as well - if(!ModelConverter.isAtomicComponent(componentRI)) { - addInnerComponentsToCache(componentCache, componentRI); - } - } - }); - } - } - - private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - String id, String fileName, Component component) { - - ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); - if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { - componentCache.put(component.getInvariantUUID(), - new ImmutableTriple<String, String, Component>(id, fileName, component)); - - if(cachedComponent != null) { - //overwriting component with newer version - log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); - } - } - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { - try { - Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component); - ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); - String mainYaml = componentInterfaceYaml.getMainYaml(); - String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); - - zip.putNextEntry(new ZipEntry(interfaceFileName)); - zip.write(mainYaml.getBytes()); - - } catch (Exception e) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - return Either.left(zip); - } - - private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { - - ComponentTypeEnum componentType = component.getComponentType(); - List<Artifact> generatedArtifacts; - List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); - - if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { - List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); - - Either<List<Artifact>, String> generatorResponse; - - if (mockGenerator) { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); - } else { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); - } - - if (generatorResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); - return Either.right(responseFormat); - } - - generatedArtifacts = generatorResponse.left().value(); - - aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); - - } - - return Either.left(aaiArtifacts); - } - - private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { - - Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; - User lastComponentUpdater; - - List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); - - String lastUpdaterUserId = component.getLastUpdaterUserId(); - Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); - - if (validateUserExists.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); - return Either.right(responseFormat); - } - - lastComponentUpdater = validateUserExists.left().value(); - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction); - } - - private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); - Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); - - return artifactsFromAAI.stream() - .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) - .filter(e -> checkAaiForUpdate(component, e)) - .collect(Collectors.toList()); - } - - private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { - ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); - - if (artifactDefinitionComp == null) { - log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); - return false; - } - - // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated - if (artifactDefinitionComp.getGenerated() == null) { - if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { - return true; - } else { - log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); - } - } else { - if (artifactDefinition.getGenerated()) { - return true; - } else { - log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); - } - } - return false; - } - - private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> aaiLabels = artifactsFromAAI.stream() - .map(ArtifactDefinition::getArtifactLabel) - .collect(Collectors.toSet()); - - List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); - - return artifactsForDeleteDeployment.stream() - .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) - .collect(Collectors.toList()); - } - - private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); - Set<String> componentInfoLabels = component.getArtifacts().keySet(); - - // If the artifact label does not exist in the service - - // store the artifact (generate uuid and version, "generated" flag is TRUE) - return artifactsFromAAI.stream() - .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - } - - private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, - boolean inTransaction) { - - String componentUniqueId = component.getUniqueId(); - ComponentTypeEnum componentType = component.getComponentType(); - - for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { - String data = gson.toJson(artDef); - String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); - String artifactUniqueId = null; - - if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) { - String artifactLabel = artDef.getArtifactLabel(); - ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); - if (artifactDefinition != null) { - artifactUniqueId = artifactDefinition.getUniqueId(); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, - null, null, user, component, shouldLock, inTransaction, false); - - if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); - - Either.right(responseFormat); - } else { - log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); - } - } - } - - return Either.left(ActionStatus.OK); - } - - private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) { - List<ArtifactDefinition> artifactDefList = new LinkedList<>(); - - for (Artifact artifact : generatorOutput) { - ArtifactDefinition newEntry = new ArtifactDefinition(); - newEntry.setArtifactName(artifact.getName()); - newEntry.setArtifactType(artifact.getType()); - newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); - newEntry.setDescription(artifact.getDescription()); - - // Normalizing the artifact label to match those stored in DB - String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); - newEntry.setArtifactLabel(normalizeArtifactLabel); - newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); - newEntry.setArtifactChecksum(artifact.getChecksum()); - // Flag that set to true in case that the artifact is generated by AI&I generator - newEntry.setGenerated(Boolean.TRUE); - - artifactDefList.add(newEntry); - } - - return artifactDefList; - } - - // List<ImmutablePair<Component, byte[] artifactBytes>> - // artifact stored by label - private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { - List<Artifact> listOfArtifactsInput = new LinkedList<>(); - for (ImmutablePair<Component, byte[]> triple : inputs) { - Component component = triple.getLeft(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - String artifactName = artifactDefinition.getArtifactName(); - String artifactType = artifactDefinition.getArtifactType(); - String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); - String artifactDescription = artifactDefinition.getDescription(); - String artifactLabel = artifactDefinition.getArtifactLabel(); - byte[] right = triple.getRight(); - // The md5 calculated on the uncoded data - String md5Hex = DigestUtils.md5Hex(right); - byte[] payload = Base64.encodeBase64(right); - String artifactVersion = artifactDefinition.getArtifactVersion(); - - Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); - convertedArtifact.setName(artifactName); - convertedArtifact.setDescription(artifactDescription); - convertedArtifact.setLabel(artifactLabel); - convertedArtifact.setVersion(artifactVersion); - - listOfArtifactsInput.add(convertedArtifact); - } - - return listOfArtifactsInput; - } - - private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { - byte[] content; - if (cassandraId == null || cassandraId.isEmpty()) { - Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); - if (exportRes.isRight()) { - log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); - return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); - } - content = exportRes.left().value().getMainYaml().getBytes(); - } else { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); - } else { - content = fromCassandra.left().value(); - } - } - return Either.left(content); - } - - private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { - Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); - } - - List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); - - if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); - } - - SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); - - return Either.left(schemaFile.getPayloadAsArray()); - } - - private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { - Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId); - - if (artifactResponse.isRight()) { - log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); - - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(convertedFromStorageResponse); - } - ESArtifactData artifactData = artifactResponse.left().value(); - return Either.left(artifactData.getDataAsArray()); - } - - private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { - final String BLOCK_0_TEMPLATE = - "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; - String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); - return readyBlock; - } - - private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; - return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); - } - - private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) { - - ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); - ArtifactTypes artifactTypes = new ArtifactTypes(); - List<ArtifactType> artifactTypesList = new LinkedList<>(); - ArtifactType otherType; - - if (type == null) { - otherType = ArtifactType.OTHER; - } else { - otherType = type; - } - - artifactTypesList.add(otherType); - artifactTypes.setArtifactTypes(artifactTypesList); - - String configJson = gson.toJson(artifactTypes); - Map<String, String> additionalParams = new HashMap<>(); - String version; - - if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { - version = component.getVersion(); - } else { - String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; - } - - additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); - GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); - - Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); - - if (!errorData.isEmpty()) { - Set<String> keySet = errorData.keySet(); - StringBuilder error = new StringBuilder(); - - for (String key : keySet) { - List<String> errorList = errorData.get(key); - log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); - error.append(key + errorList); - } - - return Either.right(error.toString()); - } - - return Either.left(generatedArtifacts.getResultData()); - } - - /** - * Extracts artifacts of VFCs from CSAR - * - * @param csar - * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace - */ - public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { - - Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); - if (csar != null) { - log.debug("************* Going to extract VFCs artifacts from Csar. "); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - csar.entrySet().stream() - // filter CSAR entry by node type artifact path - .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path - .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); - // add counter suffix to artifact labels - handleWarningMessages(collectedWarningMessages); - - } - return artifacts; - } - - /** - * Print warnings to log - * - * @param collectedWarningMessages - */ - public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { - collectedWarningMessages.entrySet().stream() - // for each vfc - .forEach(e -> e.getValue().stream() - // add each warning message to log - .forEach(args -> log.warn(e.getKey(), args.toArray()))); - - } - - private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) { - if (extractedVfcArtifact != null) { - List<ArtifactDefinition> currArtifactsList; - String vfcToscaNamespace = extractedVfcArtifact.getKey(); - if (artifacts.containsKey(vfcToscaNamespace)) { - currArtifactsList = artifacts.get(vfcToscaNamespace); - } else { - currArtifactsList = new ArrayList<>(); - artifacts.put(vfcToscaNamespace, currArtifactsList); - } - currArtifactsList.add(extractedVfcArtifact.getValue()); - } - } - - private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) { - ArtifactDefinition artifact; - String[] parsedCsarArtifactPath = entry.getKey().split("/"); - Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); - if (eitherArtifactGroupType.isLeft()) { - artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); - } else { - return null; - } - return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); - } - - private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<ArtifactGroupTypeEnum, Boolean> result; - try { - ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); - if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { - String warningMessage = "Warning - unrecognized artifact group type {} was received."; - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(groupType); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - - result = Either.right(false); - } else { - - result = Either.left(artifactGroupType); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - result = Either.right(false); - } - return result; - } - - private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { - ArtifactDefinition artifact; - artifact = new ArtifactDefinition(); - artifact.setArtifactGroupType(artifactGroupType); - artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); - artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); - artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); - artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); - artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); - artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); - artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); - return artifact; - } - - public static final class NonMetaArtifactInfo { - private final String path; - private final String artifactName; - private final String displayName; - private final String artifactLabel; - private final ArtifactTypeEnum artifactType; - private final ArtifactGroupTypeEnum artifactGroupType; - private String payloadData; - private String artifactChecksum; - private String artifactUniqueId; - - public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) { - super(); - this.path = path; - this.artifactName = ValidationUtils.normalizeFileName(artifactName); - this.artifactType = artifactType; - this.artifactGroupType = artifactGroupType; - final int pointIndex = artifactName.lastIndexOf('.'); - if (pointIndex > 0) { - displayName = artifactName.substring(0, pointIndex); - } else { - displayName = artifactName; - } - this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); - if (payloadData != null) { - this.payloadData = Base64.encodeBase64String(payloadData); - this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); - } - this.artifactUniqueId = artifactUniqueId; - } - - public String getPath() { - return path; - } - - public String getArtifactName() { - return artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public String getDisplayName() { - return displayName; - } - - public ArtifactGroupTypeEnum getArtifactGroupType() { - return artifactGroupType; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public String getPayloadData() { - return payloadData; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public String getArtifactUniqueId() { - return artifactUniqueId; - } - - public void setArtifactUniqueId(String artifactUniqueId) { - this.artifactUniqueId = artifactUniqueId; - } - - } - - /** - * This method checks the artifact GroupType & Artifact Type. <br> - * if there is any problem warning messages are added to collectedWarningMessages - * - * @param artifactPath - * @param collectedWarningMessages - * @return - */ - public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<NonMetaArtifactInfo, Boolean> ret; - try { - String[] parsedArtifactPath = artifactPath.split("/"); - // Validate Artifact Group Type - Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); - if (eitherGroupType.isLeft()) { - final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); - - // Validate Artifact Type - String artifactType = parsedArtifactPath[2]; - artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); - - String artifactFileNameType = parsedArtifactPath[3]; - ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null)); - - } else { - ret = Either.right(eitherGroupType.right().value()); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - ret = Either.right(false); - } - return ret; - - } - - private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); - } - - private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); - } - - private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); - Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; - - if(artifactGroupType != null){ - switch (artifactGroupType) { - case INFORMATIONAL: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceInformationalArtifacts(); - break; - case DEPLOYMENT: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceDeploymentArtifacts(); - break; - default: - break; - } - } - - Set<String> validArtifactTypes = null; - if(resourceValidTypeArtifacts != null){ - validArtifactTypes = resourceValidTypeArtifacts.keySet(); - } - - if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(receivedTypeName); - messageArguments.addAll(Arrays.asList(arguments)); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - } - - return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); - } - - private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ - ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); - - Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); - Set<String> keySet = componentInstancesArtifacts.keySet(); - - String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; - for (String keyAssetName : keySet) { - ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); - String pathWithAssetName = currentPath + keyAssetName + "/"; - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - } - - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, - String currentPath, boolean isInCertificationRequest) throws IOException { - Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); - //Keys are defined: - //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>. - //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" - Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); - for (String keyAssetName : componentTypeArtifactsKeys) { - ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); - ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); - String pathWithAssetName = currentPath + keyAssetName + "/"; - Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeArtifactsInfoToSpecifiedtPath.isRight()){ - return writeArtifactsInfoToSpecifiedtPath; - } - } - - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo - .getArtifactsInfo(); - Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); - - for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { - String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); - Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); - - for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { - List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); - String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; - - Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); - - if(writeArtifactDefinition.isRight()){ - return writeArtifactDefinition; - } - } - } - - return Either.left(zip); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, - String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { - - ComponentTypeEnum componentType = mainComponent.getComponentType(); - String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); - - for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { - if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE - && artifactDefinition.getArtifactType().equals(heatEnvType) || + return Either.right(responseFormat); + } + mainYaml = fromCassandra.left().value(); + + } else { + exportComponent = toscaExportUtils.exportComponent(component); + if (exportComponent.isRight()) { + log.debug("exportComponent failed", exportComponent.right().value()); + ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); + return Either.right(responseFormat); + } + ToscaRepresentation exportResult = exportComponent.left().value(); + componentYaml = exportResult.getMainYaml(); + mainYaml = componentYaml.getBytes(); + dependencies = exportResult.getDependencies(); + } + + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); + zip.write(mainYaml); + //US798487 - Abstraction of complex types + if (!ModelConverter.isAtomicComponent(component)){ + log.debug("Component {} is complex - generating abstract type for it..", component.getName()); + writeComponentInterface(component, zip, fileName); + } + + generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); + + if (dependencies == null) { + Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); + if (dependenciesRes.isRight()) { + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), + dependenciesRes.right().value()); + ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + return Either.right(responseFormat); + } + dependencies = dependenciesRes.left().value().getDependencies(); + } + + //UID <cassandraId,filename,component> + Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>(); + + if (dependencies != null && !dependencies.isEmpty()) { + for (Triple<String, String, Component> d : dependencies) { + String cassandraId = d.getMiddle(); + Component childComponent = d.getRight(); + Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); + + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + return Either.right(responseFormat); + } + + //fill innerComponentsCache + fileName = d.getLeft(); + addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); + addInnerComponentsToCache(innerComponentsCache, childComponent); + + byte[] content = entryData.left().value(); + generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); + } + + //add inner components to CSAR + for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) { + + ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); + + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); + + // add component to zip + Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), + entryData.right().value()); + return Either.right(responseFormat); + } + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ModelConverter.isAtomicComponent(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } + } + + //retrieve SDC.zip from Cassandra + Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + + if(latestSchemaFilesFromCassandra.isRight()){ + log.error("Error retrieving SDC Schema files from cassandra" ); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } + + //add files from retireved SDC.zip to Definitions folder in CSAR + Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); + + if(addSchemaFilesFromCassandra.isRight()){ + return addSchemaFilesFromCassandra; + } + + // Artifact Generation + if (component.getComponentType() == ComponentTypeEnum.SERVICE + && isInCertificationRequest) { + + List<ArtifactDefinition> aiiArtifactList; + + Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); + + if (handleAAIArtifacts.isLeft()) { + aiiArtifactList = handleAAIArtifacts.left().value(); + } else { + log.debug("AAI Artifacts handling failed"); + return Either.right(handleAAIArtifacts.right().value()); + } + + if (isInCertificationRequest) { + Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( + component, aiiArtifactList, false, true); + + if (handleAllAAIArtifactsInDataModel.isRight()) { + log.debug("AAI Artifacts handling (create, update, delete) failed"); + return Either.right(handleAllAAIArtifactsInDataModel.right().value()); + } + } + + } + + Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component); + + if (collectedComponentCsarDefinition.isRight()) { + return Either.right(collectedComponentCsarDefinition.right().value()); + } + + return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); + } + + private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ + + final int initSize = 2048; + + log.debug("Starting copy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { + + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); + } + } catch (IOException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + log.debug("Finished coppy from Schema file zip to CSAR zip"); + + return Either.left(zip); + } + + + private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, + Component childComponent) { + + List<ComponentInstance> instances = childComponent.getComponentInstances(); + + if(instances != null) { + instances.forEach(ci -> { + ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); + if (componentRecord == null) { + // all resource must be only once! + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); + if (resource.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } + Component componentRI = resource.left().value(); + + Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + if (childArtifactDefinition != null) { + //add to cache + addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); + } + + //if not atomic - insert inner components as well + if(!ModelConverter.isAtomicComponent(componentRI)) { + addInnerComponentsToCache(componentCache, componentRI); + } + } + }); + } + } + + private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, + String id, String fileName, Component component) { + + ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); + if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { + componentCache.put(component.getInvariantUUID(), + new ImmutableTriple<String, String, Component>(id, fileName, component)); + + if(cachedComponent != null) { + //overwriting component with newer version + log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); + } + } + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { + try { + Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component); + ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); + String mainYaml = componentInterfaceYaml.getMainYaml(); + String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); + + zip.putNextEntry(new ZipEntry(interfaceFileName)); + zip.write(mainYaml.getBytes()); + + } catch (Exception e) { + log.error("#writeComponentInterface - zip writing failed with error: ", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return Either.left(zip); + } + + private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { + + ComponentTypeEnum componentType = component.getComponentType(); + List<Artifact> generatedArtifacts; + List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); + + if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { + List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); + + Either<List<Artifact>, String> generatorResponse; + + if (mockGenerator) { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); + } else { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); + } + + if (generatorResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); + return Either.right(responseFormat); + } + + generatedArtifacts = generatorResponse.left().value(); + + aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); + + } + + return Either.left(aaiArtifacts); + } + + private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { + + Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; + User lastComponentUpdater; + + List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); + + String lastUpdaterUserId = component.getLastUpdaterUserId(); + Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); + + if (validateUserExists.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); + return Either.right(responseFormat); + } + + lastComponentUpdater = validateUserExists.left().value(); + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction); + } + + private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); + Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); + + return artifactsFromAAI.stream() + .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) + .filter(e -> checkAaiForUpdate(component, e)) + .collect(Collectors.toList()); + } + + private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { + ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); + + if (artifactDefinitionComp == null) { + log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); + return false; + } + + // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated + if (artifactDefinitionComp.getGenerated() == null) { + if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { + return true; + } else { + log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); + } + } else { + if (artifactDefinition.getGenerated()) { + return true; + } else { + log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); + } + } + return false; + } + + private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> aaiLabels = artifactsFromAAI.stream() + .map(ArtifactDefinition::getArtifactLabel) + .collect(Collectors.toSet()); + + List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); + + return artifactsForDeleteDeployment.stream() + .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) + .collect(Collectors.toList()); + } + + private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); + Set<String> componentInfoLabels = component.getArtifacts().keySet(); + + // If the artifact label does not exist in the service - + // store the artifact (generate uuid and version, "generated" flag is TRUE) + return artifactsFromAAI.stream() + .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + } + + private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, + boolean inTransaction) { + + String componentUniqueId = component.getUniqueId(); + ComponentTypeEnum componentType = component.getComponentType(); + + for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { + String data = gson.toJson(artDef); + String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); + String artifactUniqueId = null; + + if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) { + String artifactLabel = artDef.getArtifactLabel(); + ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); + if (artifactDefinition != null) { + artifactUniqueId = artifactDefinition.getUniqueId(); + } + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, + null, user, component, shouldLock, inTransaction, false); + + if (validateAndHandleArtifact.isRight()) { + if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); + + Either.right(responseFormat); + } else { + log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); + } + } + } + + return Either.left(ActionStatus.OK); + } + + private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) { + List<ArtifactDefinition> artifactDefList = new LinkedList<>(); + + for (Artifact artifact : generatorOutput) { + ArtifactDefinition newEntry = new ArtifactDefinition(); + newEntry.setArtifactName(artifact.getName()); + newEntry.setArtifactType(artifact.getType()); + newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); + newEntry.setDescription(artifact.getDescription()); + + // Normalizing the artifact label to match those stored in DB + String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); + newEntry.setArtifactLabel(normalizeArtifactLabel); + newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); + newEntry.setArtifactChecksum(artifact.getChecksum()); + // Flag that set to true in case that the artifact is generated by AI&I generator + newEntry.setGenerated(Boolean.TRUE); + + artifactDefList.add(newEntry); + } + + return artifactDefList; + } + + // List<ImmutablePair<Component, byte[] artifactBytes>> + // artifact stored by label + private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { + List<Artifact> listOfArtifactsInput = new LinkedList<>(); + for (ImmutablePair<Component, byte[]> triple : inputs) { + Component component = triple.getLeft(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + String artifactName = artifactDefinition.getArtifactName(); + String artifactType = artifactDefinition.getArtifactType(); + String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); + String artifactDescription = artifactDefinition.getDescription(); + String artifactLabel = artifactDefinition.getArtifactLabel(); + byte[] right = triple.getRight(); + // The md5 calculated on the uncoded data + String md5Hex = DigestUtils.md5Hex(right); + byte[] payload = Base64.encodeBase64(right); + String artifactVersion = artifactDefinition.getArtifactVersion(); + + Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); + convertedArtifact.setName(artifactName); + convertedArtifact.setDescription(artifactDescription); + convertedArtifact.setLabel(artifactLabel); + convertedArtifact.setVersion(artifactVersion); + + listOfArtifactsInput.add(convertedArtifact); + } + + return listOfArtifactsInput; + } + + private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { + byte[] content; + if (cassandraId == null || cassandraId.isEmpty()) { + Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); + if (exportRes.isRight()) { + log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); + return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); + } + content = exportRes.left().value().getMainYaml().getBytes(); + } else { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { + return Either.right(fromCassandra.right().value()); + } else { + content = fromCassandra.left().value(); + } + } + return Either.left(content); + } + + private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { + Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); + + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); + } + + List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); + + if(listOfSchemas.isEmpty()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); + } + + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + + return Either.left(schemaFile.getPayloadAsArray()); + } + + private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { + Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId); + + if (artifactResponse.isRight()) { + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); + + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(convertedFromStorageResponse); + } + ESArtifactData artifactData = artifactResponse.left().value(); + return Either.left(artifactData.getDataAsArray()); + } + + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { + final String BLOCK_0_TEMPLATE = + "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; + String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); + return readyBlock; + } + + private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { + final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; + return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); + } + + private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) { + + ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); + ArtifactTypes artifactTypes = new ArtifactTypes(); + List<ArtifactType> artifactTypesList = new LinkedList<>(); + ArtifactType otherType; + + if (type == null) { + otherType = ArtifactType.OTHER; + } else { + otherType = type; + } + + artifactTypesList.add(otherType); + artifactTypes.setArtifactTypes(artifactTypesList); + + String configJson = gson.toJson(artifactTypes); + Map<String, String> additionalParams = new HashMap<>(); + String version; + + if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { + version = component.getVersion(); + } else { + String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; + } + + additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); + GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); + + Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); + + if (!errorData.isEmpty()) { + Set<String> keySet = errorData.keySet(); + StringBuilder error = new StringBuilder(); + + for (String key : keySet) { + List<String> errorList = errorData.get(key); + log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); + error.append(key + errorList); + } + + return Either.right(error.toString()); + } + + return Either.left(generatedArtifacts.getResultData()); + } + + /** + * Extracts artifacts of VFCs from CSAR + * + * @param csar + * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace + */ + public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { + + Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); + if (csar != null) { + log.debug("************* Going to extract VFCs artifacts from Csar. "); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + csar.entrySet().stream() + // filter CSAR entry by node type artifact path + .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path + .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); + // add counter suffix to artifact labels + handleWarningMessages(collectedWarningMessages); + + } + return artifacts; + } + + /** + * Print warnings to log + * + * @param collectedWarningMessages + */ + public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { + collectedWarningMessages.entrySet().stream() + // for each vfc + .forEach(e -> e.getValue().stream() + // add each warning message to log + .forEach(args -> log.warn(e.getKey(), args.toArray()))); + + } + + private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) { + if (extractedVfcArtifact != null) { + List<ArtifactDefinition> currArtifactsList; + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + if (artifacts.containsKey(vfcToscaNamespace)) { + currArtifactsList = artifacts.get(vfcToscaNamespace); + } else { + currArtifactsList = new ArrayList<>(); + artifacts.put(vfcToscaNamespace, currArtifactsList); + } + currArtifactsList.add(extractedVfcArtifact.getValue()); + } + } + + private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) { + ArtifactDefinition artifact; + String[] parsedCsarArtifactPath = entry.getKey().split("/"); + Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); + if (eitherArtifactGroupType.isLeft()) { + artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); + } else { + return null; + } + return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); + } + + private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) { + Either<ArtifactGroupTypeEnum, Boolean> result; + try { + ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); + if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { + String warningMessage = "Warning - unrecognized artifact group type {} was received."; + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(groupType); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + + result = Either.right(false); + } else { + + result = Either.left(artifactGroupType); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + result = Either.right(false); + } + return result; + } + + private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { + ArtifactDefinition artifact; + artifact = new ArtifactDefinition(); + artifact.setArtifactGroupType(artifactGroupType); + artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); + artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); + artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); + artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); + artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); + artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); + artifact.setIsFromCsar(true); + artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); + return artifact; + } + + public static final class NonMetaArtifactInfo { + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final ArtifactTypeEnum artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private String payloadData; + private String artifactChecksum; + private String artifactUniqueId; + private final boolean isFromCsar; + + public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) { + super(); + this.path = path; + this.isFromCsar = isFromCsar; + this.artifactName = ValidationUtils.normalizeFileName(artifactName); + this.artifactType = artifactType; + this.artifactGroupType = artifactGroupType; + final int pointIndex = artifactName.lastIndexOf('.'); + if (pointIndex > 0) { + displayName = artifactName.substring(0, pointIndex); + } else { + displayName = artifactName; + } + this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); + if (payloadData != null) { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + + public String getPath() { + return path; + } + + public String getArtifactName() { + return artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public String getDisplayName() { + return displayName; + } + + public ArtifactGroupTypeEnum getArtifactGroupType() { + return artifactGroupType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public boolean isFromCsar(){ + return isFromCsar; + } + + public String getPayloadData() { + return payloadData; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public String getArtifactUniqueId() { + return artifactUniqueId; + } + + public void setArtifactUniqueId(String artifactUniqueId) { + this.artifactUniqueId = artifactUniqueId; + } + + } + + /** + * This method checks the artifact GroupType & Artifact Type. <br> + * if there is any problem warning messages are added to collectedWarningMessages + * + * @param artifactPath + * @param collectedWarningMessages + * @return + */ + public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) { + Either<NonMetaArtifactInfo, Boolean> ret; + try { + String[] parsedArtifactPath = artifactPath.split("/"); + // Validate Artifact Group Type + Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); + if (eitherGroupType.isLeft()) { + final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); + + // Validate Artifact Type + String artifactType = parsedArtifactPath[2]; + artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); + + String artifactFileNameType = parsedArtifactPath[3]; + ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true)); + + } else { + ret = Either.right(eitherGroupType.right().value()); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + ret = Either.right(false); + } + return ret; + + } + + private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); + } + + private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); + } + + private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); + Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; + + if(artifactGroupType != null){ + switch (artifactGroupType) { + case INFORMATIONAL: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceInformationalArtifacts(); + break; + case DEPLOYMENT: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceDeploymentArtifacts(); + break; + default: + break; + } + } + + Set<String> validArtifactTypes = null; + if(resourceValidTypeArtifacts != null){ + validArtifactTypes = resourceValidTypeArtifacts.keySet(); + } + + if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + + return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); + } + + private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ + ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); + + Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); + Set<String> keySet = componentInstancesArtifacts.keySet(); + + String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; + for (String keyAssetName : keySet) { + ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); + String pathWithAssetName = currentPath + keyAssetName + "/"; + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + } + + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, + String currentPath, boolean isInCertificationRequest) throws IOException { + Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); + //Keys are defined: + //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>. + //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" + Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); + for (String keyAssetName : componentTypeArtifactsKeys) { + ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); + ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); + String pathWithAssetName = currentPath + keyAssetName + "/"; + Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeArtifactsInfoToSpecifiedtPath.isRight()){ + return writeArtifactsInfoToSpecifiedtPath; + } + } + + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo + .getArtifactsInfo(); + Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); + + for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { + String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); + Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); + + for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { + List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); + String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; + + Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); + + if(writeArtifactDefinition.isRight()){ + return writeArtifactDefinition; + } + } + } + + return Either.left(zip); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, + String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { + + ComponentTypeEnum componentType = mainComponent.getComponentType(); + String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); + + for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { + if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE + && artifactDefinition.getArtifactType().equals(heatEnvType) || //this is placeholder (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){ - continue; - } - - byte[] payloadData = artifactDefinition.getPayloadData(); - String artifactFileName = artifactDefinition.getArtifactName(); - - if (payloadData == null) { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); - - if (fromCassandra.isRight()) { + continue; + } + + byte[] payloadData = artifactDefinition.getPayloadData(); + String artifactFileName = artifactDefinition.getArtifactName(); + + if (payloadData == null) { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); + + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); - log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); - continue; - } - payloadData = fromCassandra.left().value(); - } - zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); - zip.write(payloadData); - } - - return Either.left(zip); - } - - /************************************ Artifacts Structure ******************************************************************/ - /** - * The artifacts Definition saved by their structure - */ - private class ArtifactsInfo { - //Key is the type of artifacts(Informational/Deployment) - //Value is a map between an artifact type and a list of all artifacts of this type - private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; - - public ArtifactsInfo() { - this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); - } - - public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { - return artifactsInfoField; - } - - public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ - List<ArtifactDefinition> artifacts = new ArrayList<>(); - for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){ - artifacts.addAll(artifactsByType); - } - return artifacts; - } - - public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){ - artifactsInfoField.put(artifactGroup, artifactsDefinition); - } - - public boolean isEmpty() { - return artifactsInfoField.isEmpty(); - } - - } - - /** - * The artifacts of the component and of all its composed instances - * - */ - private class ComponentTypeArtifacts { - private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) - private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) - - public ComponentTypeArtifacts() { - componentArtifacts = new ArtifactsInfo(); - componentInstancesArtifacts = new HashMap<>(); - } - - public ArtifactsInfo getComponentArtifacts() { - return componentArtifacts; - } - public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { - this.componentArtifacts = artifactsInfo; - } - public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { - return componentInstancesArtifacts; - } - public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { - this.componentInstancesArtifacts = componentInstancesArtifacts; - } - - public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { - componentInstancesArtifacts.put(normalizedName, artifactsInfo); - } - - } - - private class ComponentArtifacts { - //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) - private ComponentTypeArtifacts mainTypeAndCIArtifacts; - //artifacts of all component types mapped by their tosca name - private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; - - public ComponentArtifacts(){ - mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); - componentTypeArtifacts = new HashMap<>(); - } - - public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { - return mainTypeAndCIArtifacts; - } - - public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - this.mainTypeAndCIArtifacts = componentInstanceArtifacts; - } - - public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { - return componentTypeArtifacts; - } - - public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { - this.componentTypeArtifacts = componentTypeArtifacts; - } - } - - private class CsarDefinition { - private ComponentArtifacts componentArtifacts; - - // add list of tosca artifacts and meta describes CSAR zip root - - public CsarDefinition(ComponentArtifacts componentArtifacts) { - this.componentArtifacts = componentArtifacts; - } - - public ComponentArtifacts getComponentArtifacts() { - return componentArtifacts; - } - } - - /************************************ Artifacts Structure END******************************************************************/ - - private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){ - ComponentArtifacts componentArtifacts = new ComponentArtifacts(); - Component updatedComponent = component; - - //get service to receive the AII artifacts uploaded to the service - if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { - Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); - - if(getServiceResponse.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - updatedComponent = getServiceResponse.left().value(); - } - - //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder - ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); - ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); - componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); - componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); - - Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) - //get the component instances - List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance componentInstance:componentInstances){ - //call recursive to find artifacts for all the path - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return Either.right(collectComponentInstanceArtifacts.right().value()); - } - } - } - - if(log.isDebugEnabled()){ - printResult(componentArtifacts,updatedComponent.getName()); - } - - return Either.left(new CsarDefinition(componentArtifacts)); - } - - private void printResult(ComponentArtifacts componentArtifacts, String name) { - StringBuilder result = new StringBuilder(); - result.append("Artifacts of main component " + name + "\n"); - ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - printArtifacts(componentInstanceArtifacts); - result.append("Type Artifacts\n"); - for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ - result.append("Folder " + typeArtifacts.getKey() + "\n"); - result.append(printArtifacts(typeArtifacts.getValue())); - } - - if(log.isDebugEnabled()){ - log.debug(result.toString()); - } - } - - private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - StringBuilder result = new StringBuilder(); - ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo(); - printArtifacts(componetArtifacts); - result = result.append("Resources\n"); - for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ - result.append("Folder" + resourceInstance.getKey() + "\n"); - result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); - } - - return result.toString(); - } - - private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { - StringBuilder result = new StringBuilder(); - for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){ - result.append(" " + artifactGroup.getKey().getType()); - for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){ - result.append(" " + groupArtifacts.getKey().getType()); - for (ArtifactDefinition artifact:groupArtifacts.getValue()){ - result.append(" " + artifact.getArtifactDisplayName()); - } - } - } - - return result.toString(); - } - - private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance, - Resource fetchedComponent) { - String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); - - ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); - //if there are no artifacts for this component type we need to fetch and build them - if (componentArtifactsInfo==null){ - ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); - componentArtifactsInfo = new ComponentTypeArtifacts(); - if (!componentArtifacts.isEmpty()){ - componentArtifactsInfo.setComponentArtifacts(componentArtifacts); - resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); - } - } - return componentArtifactsInfo; - } - - private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, - Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { - //1. get the component instance component - String componentUid = componentInstance.getComponentUid(); - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); - if (resource.isRight()) { - log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, - parentComponent.getComponentType().getValue(), parentComponent.getUUID(), - componentInstance.getOriginType().getComponentType().getValue(), componentUid)); - } - Resource fetchedComponent = resource.left().value(); - - //2. fill the artifacts for the current component parent type - ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); - - //3. find the artifacts specific to the instance - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); - - //4. add the instances artifacts to the component type - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); - } - if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); - } - if (!artifactsInfo.isEmpty()){ - instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); - } - - //5. do the same for all the component instances - List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance childComponentInstance:componentInstances){ - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return collectComponentInstanceArtifacts; - } - } - } - - return Either.left(true); - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts, - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); - if (componentArtifacts!=null){ - for (ArtifactDefinition artifact:componentArtifacts.values()){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> parentArtifactsByType = null; - if (parentArtifacts!=null){ - parentArtifactsByType = parentArtifacts.get(artifactType); - } - //the artifact is of instance - if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ - List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); - if (typeArtifacts == null){ - typeArtifacts = new ArrayList<>(); - artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - } - - return artifactsByTypeOfComponentInstance; - } - - private ArtifactsInfo collectComponentArtifacts(Component component) { - Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); - Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!informationalArtifactsByType.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); - } - if (!deploymentArtifactsByType.isEmpty() ){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); - } - - return artifactsInfo; - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); - for (ArtifactDefinition artifact:componentArtifacts.values()){ - if (artifact.getArtifactUUID()!=null){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); - if (typeArtifacts==null){ - typeArtifacts = new ArrayList<>(); - artifactsByType.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - return artifactsByType; - } + log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); + continue; + } + payloadData = fromCassandra.left().value(); + } + zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); + zip.write(payloadData); + } + + return Either.left(zip); + } + + /************************************ Artifacts Structure ******************************************************************/ + /** + * The artifacts Definition saved by their structure + */ + private class ArtifactsInfo { + //Key is the type of artifacts(Informational/Deployment) + //Value is a map between an artifact type and a list of all artifacts of this type + private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; + + public ArtifactsInfo() { + this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); + } + + public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { + return artifactsInfoField; + } + + public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ + List<ArtifactDefinition> artifacts = new ArrayList<>(); + for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){ + artifacts.addAll(artifactsByType); + } + return artifacts; + } + + public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){ + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + } + + /** + * The artifacts of the component and of all its composed instances + * + */ + private class ComponentTypeArtifacts { + private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) + private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) + + public ComponentTypeArtifacts() { + componentArtifacts = new ArtifactsInfo(); + componentInstancesArtifacts = new HashMap<>(); + } + + public ArtifactsInfo getComponentArtifacts() { + return componentArtifacts; + } + public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { + this.componentArtifacts = artifactsInfo; + } + public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { + return componentInstancesArtifacts; + } + public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { + this.componentInstancesArtifacts = componentInstancesArtifacts; + } + + public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { + componentInstancesArtifacts.put(normalizedName, artifactsInfo); + } + + } + + private class ComponentArtifacts { + //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) + private ComponentTypeArtifacts mainTypeAndCIArtifacts; + //artifacts of all component types mapped by their tosca name + private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; + + public ComponentArtifacts(){ + mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); + componentTypeArtifacts = new HashMap<>(); + } + + public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { + return mainTypeAndCIArtifacts; + } + + public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + this.mainTypeAndCIArtifacts = componentInstanceArtifacts; + } + + public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { + return componentTypeArtifacts; + } + + public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { + this.componentTypeArtifacts = componentTypeArtifacts; + } + } + + private class CsarDefinition { + private ComponentArtifacts componentArtifacts; + + // add list of tosca artifacts and meta describes CSAR zip root + + public CsarDefinition(ComponentArtifacts componentArtifacts) { + this.componentArtifacts = componentArtifacts; + } + + public ComponentArtifacts getComponentArtifacts() { + return componentArtifacts; + } + } + + /************************************ Artifacts Structure END******************************************************************/ + + private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){ + ComponentArtifacts componentArtifacts = new ComponentArtifacts(); + Component updatedComponent = component; + + //get service to receive the AII artifacts uploaded to the service + if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); + + if(getServiceResponse.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + updatedComponent = getServiceResponse.left().value(); + } + + //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder + ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); + ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); + componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); + componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); + + Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) + //get the component instances + List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance componentInstance:componentInstances){ + //call recursive to find artifacts for all the path + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return Either.right(collectComponentInstanceArtifacts.right().value()); + } + } + } + + if(log.isDebugEnabled()){ + printResult(componentArtifacts,updatedComponent.getName()); + } + + return Either.left(new CsarDefinition(componentArtifacts)); + } + + private void printResult(ComponentArtifacts componentArtifacts, String name) { + StringBuilder result = new StringBuilder(); + result.append("Artifacts of main component " + name + "\n"); + ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + printArtifacts(componentInstanceArtifacts); + result.append("Type Artifacts\n"); + for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ + result.append("Folder " + typeArtifacts.getKey() + "\n"); + result.append(printArtifacts(typeArtifacts.getValue())); + } + + if(log.isDebugEnabled()){ + log.debug(result.toString()); + } + } + + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + StringBuilder result = new StringBuilder(); + ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo(); + printArtifacts(componetArtifacts); + result = result.append("Resources\n"); + for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ + result.append("Folder" + resourceInstance.getKey() + "\n"); + result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); + } + + return result.toString(); + } + + private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { + StringBuilder result = new StringBuilder(); + for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){ + result.append(" " + artifactGroup.getKey().getType()); + for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){ + result.append(" " + groupArtifacts.getKey().getType()); + for (ArtifactDefinition artifact:groupArtifacts.getValue()){ + result.append(" " + artifact.getArtifactDisplayName()); + } + } + } + + return result.toString(); + } + + private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance, + Resource fetchedComponent) { + String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); + + ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); + //if there are no artifacts for this component type we need to fetch and build them + if (componentArtifactsInfo==null){ + ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); + componentArtifactsInfo = new ComponentTypeArtifacts(); + if (!componentArtifacts.isEmpty()){ + componentArtifactsInfo.setComponentArtifacts(componentArtifacts); + resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); + } + } + return componentArtifactsInfo; + } + + private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, + Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { + //1. get the component instance component + String componentUid = componentInstance.getComponentUid(); + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); + if (resource.isRight()) { + log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); + } + Resource fetchedComponent = resource.left().value(); + + //2. fill the artifacts for the current component parent type + ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); + + //3. find the artifacts specific to the instance + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + + //4. add the instances artifacts to the component type + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); + } + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); + } + if (!artifactsInfo.isEmpty()){ + instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); + } + + //5. do the same for all the component instances + List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance childComponentInstance:componentInstances){ + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return collectComponentInstanceArtifacts; + } + } + } + + return Either.left(true); + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts, + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); + if (componentArtifacts!=null){ + for (ArtifactDefinition artifact:componentArtifacts.values()){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> parentArtifactsByType = null; + if (parentArtifacts!=null){ + parentArtifactsByType = parentArtifacts.get(artifactType); + } + //the artifact is of instance + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ + List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); + if (typeArtifacts == null){ + typeArtifacts = new ArrayList<>(); + artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + } + + return artifactsByTypeOfComponentInstance; + } + + private ArtifactsInfo collectComponentArtifacts(Component component) { + Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); + Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!informationalArtifactsByType.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); + } + if (!deploymentArtifactsByType.isEmpty() ){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); + } + + return artifactsInfo; + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); + for (ArtifactDefinition artifact:componentArtifacts.values()){ + if (artifact.getArtifactUUID()!=null){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); + if (typeArtifacts==null){ + typeArtifacts = new ArrayList<>(); + artifactsByType.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + return artifactsByType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java index 083ea67769..f40ebf0e64 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java @@ -49,59 +49,59 @@ import com.google.gson.stream.JsonReader; import fj.data.Either; public class PropertyConvertor { - private static PropertyConvertor instance; - private JsonParser jsonParser = new JsonParser(); - private static Logger log = LoggerFactory.getLogger(PropertyConvertor.class.getName()); - Gson gson = new Gson(); - protected PropertyConvertor() { - - } - - public static synchronized PropertyConvertor getInstance() { - if (instance == null) { - instance = new PropertyConvertor(); - } - return instance; - } - - public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) { - - if (component instanceof Resource) { - Resource resource = (Resource) component; - List<PropertyDefinition> props = resource.getProperties(); - if (props != null) { - Map<String, ToscaProperty> properties = new HashMap<>(); - - // take only the properties of this resource - props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { + private static PropertyConvertor instance; + private JsonParser jsonParser = new JsonParser(); + private static final Logger log = LoggerFactory.getLogger(PropertyConvertor.class); + Gson gson = new Gson(); + protected PropertyConvertor() { + + } + + public static synchronized PropertyConvertor getInstance() { + if (instance == null) { + instance = new PropertyConvertor(); + } + return instance; + } + + public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) { + + if (component instanceof Resource) { + Resource resource = (Resource) component; + List<PropertyDefinition> props = resource.getProperties(); + if (props != null) { + Map<String, ToscaProperty> properties = new HashMap<>(); + + // take only the properties of this resource + props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { properties.put(property.getName(), convertProperty(dataTypes, property, false)); - }); - if (!properties.isEmpty()) { - toscaNodeType.setProperties(properties); - } - } - } - return Either.left(toscaNodeType); - } - - public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { - ToscaProperty prop = new ToscaProperty(); - - String innerType = null; - SchemaDefinition schema = property.getSchema(); - if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { - innerType = schema.getProperty().getType(); - EntrySchema eschema = new EntrySchema(); - eschema.setType(innerType); - eschema.setDescription(schema.getProperty().getDescription()); - prop.setEntry_schema(eschema); - } - log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); + }); + if (!properties.isEmpty()) { + toscaNodeType.setProperties(properties); + } + } + } + return Either.left(toscaNodeType); + } + + public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { + ToscaProperty prop = new ToscaProperty(); + + String innerType = null; + SchemaDefinition schema = property.getSchema(); + if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { + innerType = schema.getProperty().getType(); + EntrySchema eschema = new EntrySchema(); + eschema.setType(innerType); + eschema.setDescription(schema.getProperty().getDescription()); + prop.setEntry_schema(eschema); + } + log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); Object convertedObj = convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes); if (convertedObj != null) { prop.setDefaultp(convertedObj); } - prop.setType(property.getType()); + prop.setType(property.getType()); prop.setDescription(property.getDescription()); if (isCapabiltyProperty) { prop.setStatus(property.getStatus()); @@ -109,91 +109,91 @@ public class PropertyConvertor { } return prop; - } - - public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); - if (StringUtils.isEmpty(value)) { - value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); - if(StringUtils.isEmpty(value)){ - return null; - } - } - try { - ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); - ToscaValueConverter innerConverter = null; - Boolean isScalar = true; - - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - if (type == null) { - log.trace("isn't prederfined type, get from all data types"); - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (innerType == null) { - innerType = propertyType; - } - - if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { - log.trace("This is scalar type. get suitable converter for type {}", type); - innerConverter = type.getValueConverter(); - } else { - isScalar = false; - } - } else { - ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); - if (typeIfScalar == null) { - isScalar = false; - } - - innerConverter = type.getValueConverter(); - if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { - return innerConverter.convertToToscaValue(value, innerType, dataTypes); - } - } - JsonElement jsonElement = null; - - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - - jsonElement = jsonParser.parse(jsonReader); - - if (value.equals("")) { - return value; - } - - if (jsonElement.isJsonPrimitive() && isScalar) { - log.trace("It's well defined type. convert it"); - ToscaValueConverter converter = type.getValueConverter(); - return converter.convertToToscaValue(value, innerType, dataTypes); - } else { - log.trace("It's data type or inputs in primitive type. convert as map"); - Object convertedValue; - if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - if (isScalar) { - // complex json for scalar type - convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); - } else { - if (innerConverter != null) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); - } - } - } - return convertedValue; - } - - } catch (Exception e) { - log.debug("convertToToscaValue failed to parse json value :", e); - return null; - } - - } - - private boolean valueStartsWithNonJsonChar(String value) { - return value.startsWith("/") || value.startsWith(":"); - } + } + + public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); + if (StringUtils.isEmpty(value)) { + value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); + if(StringUtils.isEmpty(value)){ + return null; + } + } + try { + ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); + ToscaValueConverter innerConverter = null; + Boolean isScalar = true; + + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + if (type == null) { + log.trace("isn't prederfined type, get from all data types"); + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (innerType == null) { + innerType = propertyType; + } + + if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { + log.trace("This is scalar type. get suitable converter for type {}", type); + innerConverter = type.getValueConverter(); + } else { + isScalar = false; + } + } else { + ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); + if (typeIfScalar == null) { + isScalar = false; + } + + innerConverter = type.getValueConverter(); + if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { + return innerConverter.convertToToscaValue(value, innerType, dataTypes); + } + } + JsonElement jsonElement = null; + + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + + jsonElement = jsonParser.parse(jsonReader); + + if (value.equals("")) { + return value; + } + + if (jsonElement.isJsonPrimitive() && isScalar) { + log.trace("It's well defined type. convert it"); + ToscaValueConverter converter = type.getValueConverter(); + return converter.convertToToscaValue(value, innerType, dataTypes); + } else { + log.trace("It's data type or inputs in primitive type. convert as map"); + Object convertedValue; + if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + if (isScalar) { + // complex json for scalar type + convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); + } else { + if (innerConverter != null) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); + } + } + } + return convertedValue; + } + + } catch (Exception e) { + log.debug("convertToToscaValue failed to parse json value :", e); + return null; + } + + } + + private boolean valueStartsWithNonJsonChar(String value) { + return value.startsWith("/") || value.startsWith(":"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java index 94dd559d2d..c3acb43186 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.tosca; public enum ToscaError { - NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR + NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index c37c15f694..05be7f9cda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -20,19 +20,7 @@ package org.openecomp.sdc.be.tosca; -import java.beans.IntrospectionException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -44,42 +32,16 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; -import org.openecomp.sdc.be.tosca.model.IToscaMetadata; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaMetadata; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; -import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata; +import org.openecomp.sdc.be.tosca.model.*; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,1119 +59,1158 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import fj.data.Either; +import java.beans.IntrospectionException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-export-handler") public class ToscaExportHandler { - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - @Autowired - private CapabiltyRequirementConvertor capabiltyRequirementConvertor; - private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); - Map<String, Component> originComponents = new HashMap<>(); - - private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); - - public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; - public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; - public static final String IMPORTS_FILE_KEY = "file"; - public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; - public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; - public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; - public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; - public static final String VF_MODULE_DESC_KEY = "vf_module_description"; - public static final String VOLUME_GROUP_KEY = "volume_group"; - public static final String VF_MODULE_TYPE_BASE = "Base"; - public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; - private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; - private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; - protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager - .getConfigurationManager().getConfiguration().getDefaultImports(); - - public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) { - - Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); - Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, - nodeTypes); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { - CustomRepresenter representer = new CustomRepresenter(); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(false); - options.setPrettyFlow(true); - - options.setDefaultFlowStyle(FlowStyle.FLOW); - options.setCanonical(false); - - representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); - - representer.setPropertyUtils(new UnsortedPropertyUtils()); - Yaml yaml = new Yaml(representer, options); - - String yamlAsString = yaml.dumpAsMap(toscaTemplate); - - StringBuilder sb = new StringBuilder(); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append(yamlAsString); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - - ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); - toscaRepresentation.setMainYaml(sb.toString()); - toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); - - return toscaRepresentation; - } - - public Either<ToscaTemplate, ToscaError> getDependencies(Component component) { - ToscaTemplate toscaTemplate = new ToscaTemplate(null); - Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, - toscaTemplate); - if (fillImports.isRight()) { - return Either.right(fillImports.right().value()); - } - return Either.left(fillImports.left().value().left); - } - - private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - log.trace("start tosca export for {}", component.getUniqueId()); - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - - toscaTemplate.setMetadata(convertMetadata(component)); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); - if (ModelConverter.isAtomicComponent(component)) { - log.trace("convert component as node type"); - return convertNodeType(component, toscaTemplate, nodeTypes); - } else { - log.trace("convert component as topology template"); - return convertToscaTemplate(component, toscaTemplate); - } - - } - - private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) { - - Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, - toscaNode); - if (importsRes.isRight()) { - return Either.right(importsRes.right().value()); - } - toscaNode = importsRes.left().value().left; - Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component); - if (nodeTypesMapEither.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - nodeTypesMapEither.right().value()); - return Either.right(nodeTypesMapEither.right().value()); - } - Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value(); - if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) - toscaNode.setNode_types(nodeTypesMap); - - Map<String, Component> componentCache = importsRes.left().value().right; - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - - ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); - - Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes); - if (inputs.isRight()) { - return Either.right(inputs.right().value()); - } - topologyTemplate = inputs.left().value(); - - List<ComponentInstance> componentInstances = component.getComponentInstances(); - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component - .getComponentInstancesProperties(); - List<GroupDefinition> groups = component.getGroups(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component, - componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); - if (nodeTemplates.isRight()) { - return Either.right(nodeTemplates.right().value()); - } - log.debug("node templates converted"); - - topologyTemplate.setNode_templates(nodeTemplates.left().value()); - } - Map<String, ToscaGroupTemplate> groupsMap; - if (groups != null && !groups.isEmpty()) { - groupsMap = new HashMap<>(); - for (GroupDefinition group : groups) { - boolean addToTosca = true; - if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - List<String> artifacts = group.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - } - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroup(group); - groupsMap.put(group.getName(), toscaGroup); - } - - } - log.debug("groups converted"); - topologyTemplate.addGroups(groupsMap); - } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - substitutionMapping.setNode_type(toscaResourceName); - - Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - substitutionMapping = capabilities.left().value(); - - Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor - .convertSubstitutionMappingRequirements(originComponents, component, substitutionMapping); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - substitutionMapping = requirements.left().value(); - - topologyTemplate.setSubstitution_mappings(substitutionMapping); - - toscaNode.setTopology_template(topologyTemplate); - return Either.left(toscaNode); - } - - private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, - ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) { - if (log.isDebugEnabled()) - log.debug("fillInputs for component {}", component.getUniqueId()); - List<InputDefinition> inputDef = component.getInputs(); - Map<String, ToscaProperty> inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - topologyTemplate.setInputs(inputs); - } - } - return Either.left(topologyTemplate); - } - - private ToscaMetadata convertMetadata(Component component) { - return convertMetadata(component, false, null); - } - - private ToscaMetadata convertMetadata(Component component, boolean isInstance, - ComponentInstance componentInstance) { - ToscaMetadata toscaMetadata = new ToscaMetadata(); - toscaMetadata.setInvariantUUID(component.getInvariantUUID()); - toscaMetadata.setUUID(component.getUUID()); - toscaMetadata.setDescription(component.getDescription()); - toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - List<CategoryDefinition> categories = component.getCategories(); - CategoryDefinition categoryDefinition = categories.get(0); - toscaMetadata.setCategory(categoryDefinition.getName()); - - if (isInstance) { - toscaMetadata.setVersion(component.getVersion()); - toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); - if (componentInstance.getSourceModelInvariant() != null - && !componentInstance.getSourceModelInvariant().isEmpty()) { - toscaMetadata.setVersion(componentInstance.getComponentVersion()); - toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); - toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); - toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); - toscaMetadata.setName( - componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); - toscaMetadata.setDescription(componentInstance.getDescription()); - } - - } - switch (component.getComponentType()) { - case RESOURCE: - Resource resource = (Resource) component; - - if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); - } else - toscaMetadata.setType(resource.getResourceType().name()); - toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); - toscaMetadata.setResourceVendor(resource.getVendorName()); - toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); - toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); - break; - case SERVICE: - Service service = (Service) component; - toscaMetadata.setType(component.getComponentType().getValue()); - toscaMetadata.setServiceType(service.getServiceType()); - toscaMetadata.setServiceRole(service.getServiceRole()); - toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); - if (!isInstance) { - // DE268546 - toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); - } - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - } - return toscaMetadata; - } - - private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, - ToscaTemplate toscaTemplate) { - - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, Component> componentCache = new HashMap<>(); - - if (!ModelConverter.isAtomicComponent(component)) { - List<ComponentInstance> componentInstances = component.getComponentInstances(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null - ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); - - List<Triple<String, String, Component>> dependecies = new ArrayList<>(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - Map<String, Map<String, String>> importsListMember = new HashMap<>(); - Map<String, String> interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); - StringBuilder keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(component.getName()); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - additionalImports.add(importsListMember); - - componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); - originComponents.putAll(componentCache); - toscaTemplate.setDependencies(dependecies); - toscaTemplate.setImports(additionalImports); - } - } else { - log.debug("currently imports supported for VF and service only"); - } - return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache)); - } - - private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports, - List<Triple<String, String, Component>> dependecies, ComponentInstance ci) { - Map<String, String> files = new HashMap<>(); - Map<String, Map<String, String>> importsListMember = new HashMap<>(); - StringBuilder keyNameBuilder; - - Component componentRI = componentCache.get(ci.getComponentUid()); - if (componentRI == null) { - // all resource must be only once! - Either<Component, StorageOperationStatus> resource = toscaOperationFacade - .getToscaFullElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component fetchedComponent = resource.left().value(); - componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); - componentRI = fetchedComponent; - - Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); - if (artifactDefinition != null) { - String artifactName = artifactDefinition.getArtifactName(); - files.put(IMPORTS_FILE_KEY, artifactName); - keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(ci.getComponentName()); - importsListMember.put(keyNameBuilder.toString(), files); - imports.add(importsListMember); - dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, - artifactDefinition.getEsId(), fetchedComponent)); - - if (!ModelConverter.isAtomicComponent(componentRI)) { - importsListMember = new HashMap<>(); - Map<String, String> interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - imports.add(importsListMember); - } - } - } - } - - public static String getInterfaceFilename(String artifactName) { - return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; - } - - private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, - dataTypes); - if (properties.isRight()) { - return Either.right(properties.right().value()); - } - toscaNodeType = properties.left().value(); - log.debug("Properties converted for {}", component.getUniqueId()); - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - - List<InputDefinition> inputDef = component.getInputs(); - Map<String, ToscaProperty> inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - toscaNodeType.setProperties(inputs); - } - } - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType, - Map<String, DataTypeDefinition> dataTypes) { - Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - toscaNodeType = capabilities.left().value(); - log.debug("Capabilities converted for {}", component.getUniqueId()); - - Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, - toscaNodeType); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - toscaNodeType = requirements.left().value(); - log.debug("Requirements converted for {}", component.getUniqueId()); - - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - - nodeTypes.put(toscaResourceName, toscaNodeType); - toscaNode.setNode_types(nodeTypes); - log.debug("finish convert node type for {}", component.getUniqueId()); - return Either.left(toscaNode); - } - - private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component, - List<ComponentInstance> componentInstances, - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, - Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes, - ToscaTopolgyTemplate topologyTemplate) { - - Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null; - log.debug("start convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>(); - Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs(); - - Map<String, ToscaGroupTemplate> groupsMap = null; - for (ComponentInstance componentInstance : componentInstances) { - ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); - nodeTemplate.setType(componentInstance.getToscaComponentName()); - - Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor - .getOriginComponent(componentCache, componentInstance); - if (originComponentRes.isRight()) { - convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - break; - } - Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, - componentInstance, component.getComponentInstancesRelations(), nodeTemplate, - originComponentRes.left().value()); - if (requirements.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - String instanceUniqueId = componentInstance.getUniqueId(); - log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); - - nodeTemplate = requirements.left().value(); - - Component componentOfInstance = componentCache.get(componentInstance.getActualComponentUid()); - nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance)); - - Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor - .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); - if (capabilities.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); - - nodeTemplate = capabilities.left().value(); - Map<String, Object> props = new HashMap<>(); - - if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) { - // Adds the properties of parent component to map - addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props); - } - - if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { - addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, - instanceUniqueId, props); - } - - if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { - addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, - props); - } - if (props != null && !props.isEmpty()) { - nodeTemplate.setProperties(props); - } - - List<GroupInstance> groupInstances = componentInstance.getGroupInstances(); - if (groupInstances != null) { - if (groupsMap == null) { - groupsMap = new HashMap<>(); - } - for (GroupInstance groupInst : groupInstances) { - boolean addToTosca = true; - - List<String> artifacts = groupInst.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); - groupsMap.put(groupInst.getName(), toscaGroup); - } - } - } - - nodeTemplates.put(componentInstance.getName(), nodeTemplate); - } - if (groupsMap != null) { - log.debug("instance groups added"); - topologyTemplate.addGroups(groupsMap); - } - - if (convertNodeTemplatesRes == null) { - convertNodeTemplatesRes = Either.left(nodeTemplates); - } - log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - return convertNodeTemplatesRes; - } - - private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes, - Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance, - String instanceUniqueId, Map<String, Object> props) { - - List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId); - if (instanceInputsList != null) { - instanceInputsList.forEach(input -> { - - Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty() - ? input.getValue() : input.getDefaultValue(); - convertAndAddValue(dataTypes, componentInstance, props, input, supplier); - }); - } - } - - private void addPropertiesOfComponentInstance( - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, - Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId, - Map<String, Object> props) { - - if (!MapUtils.isEmpty(componentInstancesProperties)) { - componentInstancesProperties.get(instanceUniqueId).stream() - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getValue())); - } - } - - private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes, - ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) { - - List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties(); - if (!CollectionUtils.isEmpty(componentProperties)) { - componentProperties.stream() - // Filters out properties with empty default values - .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getDefaultValue())); - } - } - - /** - * @param dataTypes - * @param componentInstance - * @param props - * @param prop - * @param supplier - */ - private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, - Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) { - Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); - if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { - props.put(prop.getName(), convertedValue); - } - } - - private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, - ComponentInstance componentInstance, T input, Supplier<String> supplier) { - log.debug("Convert property or input value {} for instance {}", input.getName(), - componentInstance.getUniqueId()); - String propertyType = input.getType(); - String innerType = null; - if (input.getSchema() != null && input.getSchema().getProperty() != null) { - innerType = input.getSchema().getProperty().getType(); - } - return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); - } - - private ToscaGroupTemplate convertGroup(GroupDefinition group) { - - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - Map<String, String> members = group.getMembers(); - if (members != null) - toscaGroup.setMembers(new ArrayList<String>(members.keySet())); - - Supplier<String> supplGroupType = () -> group.getType(); - Supplier<String> supplDescription = () -> group.getDescription(); - Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties(); - Supplier<String> supplgroupName = () -> group.getName(); - Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID(); - Supplier<String> supplGroupUUID = () -> group.getGroupUUID(); - Supplier<String> supplVersion = () -> group.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - - Supplier<String> supplGroupType = () -> groupInstance.getType(); - Supplier<String> supplDescription = () -> groupInstance.getDescription(); - Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance - .convertToGroupInstancesProperties(); - Supplier<String> supplgroupName = () -> groupInstance.getGroupName(); - Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID(); - Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID(); - Supplier<String> supplVersion = () -> groupInstance.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - - toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props, - Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID, - Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) { - boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; - toscaGroup.setType(groupType.get()); - - IToscaMetadata toscaMetadata; - if (!isVfModule) { - toscaMetadata = new ToscaMetadata(); - } else { - toscaMetadata = new VfModuleToscaMetadata(); - - Map<String, Object> properties = fillGroupProperties(props.get()); - if (!properties.containsKey(VF_MODULE_DESC_KEY) - || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { - properties.put(VF_MODULE_DESC_KEY, description.get()); - } - toscaGroup.setProperties(properties); - } - toscaMetadata.setName(groupName.get()); - toscaMetadata.setInvariantUUID(invariantUUID.get()); - toscaMetadata.setUUID(groupUUID.get()); - toscaMetadata.setVersion(version.get()); - return toscaMetadata; - } - - private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) { - Map<String, Object> properties = new HashMap<>(); - if (groupProps != null) { - for (GroupProperty gp : groupProps) { - if (gp.getName().equals(Constants.IS_BASE)) { - Boolean isBase = Boolean.parseBoolean(gp.getValue()); - String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; - properties.put(VF_MODULE_TYPE_KEY, type); - } else { - Object value = null; - String type = gp.getType(); - - switch (type) { - case "integer": - if (gp.getValue() != null) { - value = Integer.valueOf(gp.getValue()); - } - break; - case "boolean": - if (gp.getValue() != null) { - value = Boolean.valueOf(gp.getValue()); - } - break; - - default: - value = gp.getValue(); - break; - } - properties.put(gp.getName(), value); - } - } - } - return properties; - } - - private ToscaNodeType createNodeType(Component component) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - if (ModelConverter.isAtomicComponent(component)) { - if (((Resource) component).getDerivedFrom() != null) { - toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); - } - toscaNodeType.setDescription(component.getDescription()); // or - // name?? - } else { - String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() - : "tosca.nodes.Root"; - toscaNodeType.setDerived_from(derivedFrom); - } - return toscaNodeType; - } - - private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Component container) { - - Map<String, ToscaNodeType> nodeTypesMap = null; - Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap); - - List<ComponentInstance> componetInstances = container.getComponentInstances(); - - if (componetInstances == null || componetInstances.isEmpty()) - return res; - Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>(); - List<ComponentInstance> proxyInst = componetInstances.stream() - .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) - .collect(Collectors.toList()); - if (proxyInst != null && !proxyInst.isEmpty()) { - for (ComponentInstance inst : proxyInst) { - serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); - } - } - - if (serviceProxyInstanceList.isEmpty()) - return res; - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreComponentInstances(false); - Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade - .getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - serviceProxyOrigin.right().value()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - Component origComponent = serviceProxyOrigin.left().value(); - - nodeTypesMap = new HashMap<>(); - for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) { - Component serviceComponent = null; - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - Either<Component, StorageOperationStatus> service = toscaOperationFacade - .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); - if (service.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } else - serviceComponent = service.left().value(); - - ToscaNodeType toscaNodeType = createProxyNodeType(origComponent, serviceComponent, entryProxy.getValue()); - nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); - } - - return Either.left(nodeTypesMap); - } - - private ToscaNodeType createProxyNodeType(Component origComponent, Component proxyComponent, - ComponentInstance instance) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - String derivedFrom = ((Resource) origComponent).getToscaResourceName(); - - toscaNodeType.setDerived_from(derivedFrom); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - } - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor - .convertProxyCapabilities(origComponent, proxyComponent, instance, dataTypes); - - toscaNodeType.setCapabilities(capabilities); - - return toscaNodeType; - } - - private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, - ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, - ToscaNodeTemplate nodeTypeTemplate, Component originComponent) { - - List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); - if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)) { - log.debug("Failed to convert component instance requirements for the component instance {}. ", - componentInstance.getName()); - return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - if (!toscaRequirements.isEmpty()) { - nodeTypeTemplate.setRequirements(toscaRequirements); - } - log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); - return Either.left(nodeTypeTemplate); - } - - private boolean addRequirements(Component component, ComponentInstance componentInstance, - List<RequirementCapabilityRelDef> relations, Component originComponent, - List<Map<String, ToscaTemplateRequirement>> toscaRequirements) { - boolean result; - List<RequirementCapabilityRelDef> filteredRelations = relations.stream() - .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(filteredRelations)) { - result = true; - } else { - result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, - component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent(); - } - return result; - } - - private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, - List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel, - List<Map<String, ToscaTemplateRequirement>> toscaRequirements) { - - boolean result = true; - Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements(); - RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); - Either<Component, StorageOperationStatus> getOriginRes = null; - Optional<RequirementDefinition> reqOpt = null; - Component toOriginComponent = null; - Optional<CapabilityDefinition> cap = null; - - ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) - .findFirst().orElse(null); - if (toInstance == null) { - log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), - rel.getToNode()); - result = false; - } - if (result) { - reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, toInstance.getUniqueId()); - if (!reqOpt.isPresent()) { - log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - filter.setIgnoreCapabilities(false); - getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); - if (getOriginRes.isRight()) { - log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", - reqOpt.get().getName(), toInstance.getActualComponentUid()); - result = false; - } - } - if (result) { - toOriginComponent = getOriginRes.left().value(); - cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() - .filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst(); - if (!cap.isPresent()) { - cap = findCapability(reqMap, reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); - if(!cap.isPresent()){ - result = false; - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - } - if (result) { - result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), - reqOpt.get(), reqAndRelationshipPair, toInstance); - } - return result; - } - - private Optional<CapabilityDefinition> findCapability(Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { - Optional<CapabilityDefinition> cap = Optional.empty(); - Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny(); - if (findAny.isPresent()) { - RequirementDefinition reqDefinition = findAny.get(); - cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(reqDefinition.getCapability())).findFirst(); - if (!cap.isPresent()) { - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - return cap; - } - - private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance) { - boolean result = true; - Either<String, Boolean> buildReqNameRes = null; - Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, - toOriginComponent, capability.getPath(), reqAndRelationshipPair.getCapability()); - if (buildCapNameRes.isRight()) { - log.debug( - "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - result = false; - } - if (result) { - buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, fromOriginComponent, - requirement.getPath(), reqAndRelationshipPair.getRequirement()); - if (buildReqNameRes.isRight()) { - log.debug( - "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); - Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); - toscaRequirement.setNode(toInstance.getName()); - toscaRequirement.setCapability(buildCapNameRes.left().value()); - toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); - toscaRequirements.add(toscaReqMap); - } - return result; - } - - private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String toInstanceId) { - for(List<RequirementDefinition> reqList: reqMap.values()){ - Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, toInstanceId)).findFirst(); - if(reqOpt.isPresent()){ - return reqOpt; - } - } - return Optional.empty(); - } - - /** - * Allows detecting the requirement belonging to the received relationship - * The detection logic is: A requirement belongs to a relationship IF 1.The - * name of the requirement equals to the "requirement" field of the - * relation; AND 2. In case of a non-atomic resource, OwnerId of the - * requirement equals to requirementOwnerId of the relation OR uniqueId of - * toInstance equals to capabilityOwnerId of the relation - * - * @param fromOriginComponent - * @param reqAndRelationshipPair - * @param requirement - * @param toInstanceId - * @return - */ - private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) - return false; - if (!ModelConverter.isAtomicComponent(originComponent)) - return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, toInstanceId); - return true; - } - - private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils.equals(toInstanceId, reqAndRelationshipPair.getCapabilityOwnerId()); - } - - private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, - SubstitutionMapping substitutionMappings) { - - Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); - Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor - .convertSubstitutionMappingCapabilities(originComponents, component); - if (toscaCapabilitiesRes.isRight()) { - result = Either.right(toscaCapabilitiesRes.right().value()); - log.error("Failed convert capabilities for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { - substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); - log.debug("Finish convert capabilities for the component {}. ", component.getName()); - } - log.debug("Finished to convert capabilities for the component {}. ", component.getName()); - return result; - } - - private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, - Map<String, DataTypeDefinition> dataTypes) { - Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, - dataTypes); - if (!toscaCapabilities.isEmpty()) { - nodeType.setCapabilities(toscaCapabilities); - } - log.debug("Finish convert Capabilities for node type"); - - return Either.left(nodeType); - } - - private static class CustomRepresenter extends Representer { - public CustomRepresenter() { - super(); - // null representer is exceptional and it is stored as an instance - // variable. - this.nullRepresenter = new RepresentNull(); - - } - - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, - Tag customTag) { - if (propertyValue == null) { - return null; - } else { - // skip not relevant for Tosca property - if ("dependencies".equals(property.getName())) { - return null; - } - NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - - return "_defaultp_".equals(property.getName()) - ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; - } - } - - @Override - protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { - // remove the bean type from the output yaml (!! ...) - if (!classTags.containsKey(javaBean.getClass())) - addClassTag(javaBean.getClass(), Tag.MAP); - - return super.representJavaBean(properties, javaBean); - } - - private class RepresentNull implements Represent { - @Override - public Node representData(Object data) { - // possible values are here http://yaml.org/type/null.html - return representScalar(Tag.NULL, ""); - } - } - } - - private static class UnsortedPropertyUtils extends PropertyUtils { - @Override - protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values(); - return new LinkedHashSet<>(fields); - } - } + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private CapabiltyRequirementConvertor capabiltyRequirementConvertor; + private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); + + private static final Logger log = LoggerFactory.getLogger(ToscaExportHandler.class); + + public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; + public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; + public static final String IMPORTS_FILE_KEY = "file"; + public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; + public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; + public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; + public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; + public static final String VF_MODULE_DESC_KEY = "vf_module_description"; + public static final String VOLUME_GROUP_KEY = "volume_group"; + public static final String VF_MODULE_TYPE_BASE = "Base"; + public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; + private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; + private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; + protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager + .getConfigurationManager().getConfiguration().getDefaultImports(); + + public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) { + + Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, + nodeTypes); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { + CustomRepresenter representer = new CustomRepresenter(); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(false); + options.setPrettyFlow(true); + + options.setDefaultFlowStyle(FlowStyle.FLOW); + options.setCanonical(false); + + representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); + + representer.setPropertyUtils(new UnsortedPropertyUtils()); + Yaml yaml = new Yaml(representer, options); + + String yamlAsString = yaml.dumpAsMap(toscaTemplate); + + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append(yamlAsString); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + + ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); + toscaRepresentation.setMainYaml(sb.toString()); + toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); + + return toscaRepresentation; + } + + public Either<ToscaTemplate, ToscaError> getDependencies(Component component) { + ToscaTemplate toscaTemplate = new ToscaTemplate(null); + Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, + toscaTemplate); + if (fillImports.isRight()) { + return Either.right(fillImports.right().value()); + } + return Either.left(fillImports.left().value().left); + } + + private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + log.trace("start tosca export for {}", component.getUniqueId()); + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + + toscaTemplate.setMetadata(convertMetadata(component)); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + if (ModelConverter.isAtomicComponent(component)) { + log.trace("convert component as node type"); + return convertNodeType(component, toscaTemplate, nodeTypes); + } else { + log.trace("convert component as topology template"); + return convertToscaTemplate(component, toscaTemplate); + } + + } + + private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) { + + Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, + toscaNode); + if (importsRes.isRight()) { + return Either.right(importsRes.right().value()); + } + toscaNode = importsRes.left().value().left; + Map<String, Component> componentCache = importsRes.left().value().right; + Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component ); + if (nodeTypesMapEither.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + nodeTypesMapEither.right().value()); + return Either.right(nodeTypesMapEither.right().value()); + } + Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value(); + if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) + toscaNode.setNode_types(nodeTypesMap); + + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + + Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes); + if (inputs.isRight()) { + return Either.right(inputs.right().value()); + } + topologyTemplate = inputs.left().value(); + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component + .getComponentInstancesProperties(); + List<GroupDefinition> groups = component.getGroups(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component, + componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + if (nodeTemplates.isRight()) { + return Either.right(nodeTemplates.right().value()); + } + log.debug("node templates converted"); + + topologyTemplate.setNode_templates(nodeTemplates.left().value()); + } + Map<String, ToscaGroupTemplate> groupsMap; + if (groups != null && !groups.isEmpty()) { + groupsMap = new HashMap<>(); + for (GroupDefinition group : groups) { + boolean addToTosca = true; + if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + List<String> artifacts = group.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + } + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroup(group); + groupsMap.put(group.getName(), toscaGroup); + } + + } + log.debug("groups converted"); + topologyTemplate.addGroups(groupsMap); + } + SubstitutionMapping substitutionMapping = new SubstitutionMapping(); + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + substitutionMapping.setNode_type(toscaResourceName); + + Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + substitutionMapping = capabilities.left().value(); + + Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor + .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + substitutionMapping = requirements.left().value(); + + topologyTemplate.setSubstitution_mappings(substitutionMapping); + + toscaNode.setTopology_template(topologyTemplate); + return Either.left(toscaNode); + } + + private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, + ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) { + if (log.isDebugEnabled()) + log.debug("fillInputs for component {}", component.getUniqueId()); + List<InputDefinition> inputDef = component.getInputs(); + Map<String, ToscaProperty> inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + topologyTemplate.setInputs(inputs); + } + } + return Either.left(topologyTemplate); + } + + private ToscaMetadata convertMetadata(Component component) { + return convertMetadata(component, false, null); + } + + private ToscaMetadata convertMetadata(Component component, boolean isInstance, + ComponentInstance componentInstance) { + ToscaMetadata toscaMetadata = new ToscaMetadata(); + toscaMetadata.setInvariantUUID(component.getInvariantUUID()); + toscaMetadata.setUUID(component.getUUID()); + toscaMetadata.setDescription(component.getDescription()); + toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + List<CategoryDefinition> categories = component.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + toscaMetadata.setCategory(categoryDefinition.getName()); + + if (isInstance) { + toscaMetadata.setVersion(component.getVersion()); + toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); + if (componentInstance.getSourceModelInvariant() != null + && !componentInstance.getSourceModelInvariant().isEmpty()) { + toscaMetadata.setVersion(componentInstance.getComponentVersion()); + toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); + toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); + toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); + toscaMetadata.setName( + componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); + toscaMetadata.setDescription(componentInstance.getDescription()); + } + + } + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource) component; + + if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); + } else + toscaMetadata.setType(resource.getResourceType().name()); + toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); + toscaMetadata.setResourceVendor(resource.getVendorName()); + toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); + toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); + break; + case SERVICE: + Service service = (Service) component; + toscaMetadata.setType(component.getComponentType().getValue()); + toscaMetadata.setServiceType(service.getServiceType()); + toscaMetadata.setServiceRole(service.getServiceRole()); + toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); + if (!isInstance) { + // DE268546 + toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); + } + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + } + return toscaMetadata; + } + + private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, + ToscaTemplate toscaTemplate) { + + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map<String, Component> componentCache = new HashMap<>(); + + if (!ModelConverter.isAtomicComponent(component)) { + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null + ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); + + List<Triple<String, String, Component>> dependecies = new ArrayList<>(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + Map<String, Map<String, String>> importsListMember = new HashMap<>(); + Map<String, String> interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); + StringBuilder keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(component.getName()); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + additionalImports.add(importsListMember); + + componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); + toscaTemplate.setDependencies(dependecies); + toscaTemplate.setImports(additionalImports); + } + } else { + log.debug("currently imports supported for VF and service only"); + } + return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache)); + } + + private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports, + List<Triple<String, String, Component>> dependecies, ComponentInstance ci) { + Map<String, String> files = new HashMap<>(); + Map<String, Map<String, String>> importsListMember = new HashMap<>(); + StringBuilder keyNameBuilder; + + Component componentRI = componentCache.get(ci.getComponentUid()); + if (componentRI == null) { + // all resource must be only once! + Either<Component, StorageOperationStatus> resource = toscaOperationFacade + .getToscaFullElement(ci.getComponentUid()); + if ((resource.isRight()) && (log.isDebugEnabled())) { + log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + return ; + } + + Component fetchedComponent = resource.left().value(); + componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); + + if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){ + Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade + .getToscaFullElement(ci.getSourceModelUid()); + if (sourceService.isRight() && (log.isDebugEnabled())) { + log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId()); + } + Component fetchedSource = sourceService.left().value(); + componentCache.put(fetchedSource.getUniqueId(), fetchedSource); + } + + componentRI = fetchedComponent; + + Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); + if (artifactDefinition != null) { + String artifactName = artifactDefinition.getArtifactName(); + files.put(IMPORTS_FILE_KEY, artifactName); + keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(ci.getComponentName()); + importsListMember.put(keyNameBuilder.toString(), files); + imports.add(importsListMember); + dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, + artifactDefinition.getEsId(), fetchedComponent)); + + if (!ModelConverter.isAtomicComponent(componentRI)) { + importsListMember = new HashMap<>(); + Map<String, String> interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + imports.add(importsListMember); + } + } + } + } + + public static String getInterfaceFilename(String artifactName) { + return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + } + + private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, + dataTypes); + if (properties.isRight()) { + return Either.right(properties.right().value()); + } + toscaNodeType = properties.left().value(); + log.debug("Properties converted for {}", component.getUniqueId()); + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + + List<InputDefinition> inputDef = component.getInputs(); + Map<String, ToscaProperty> inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + toscaNodeType.setProperties(inputs); + } + } + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType, + Map<String, DataTypeDefinition> dataTypes) { + Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + toscaNodeType = capabilities.left().value(); + log.debug("Capabilities converted for {}", component.getUniqueId()); + + Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, + toscaNodeType); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + toscaNodeType = requirements.left().value(); + log.debug("Requirements converted for {}", component.getUniqueId()); + + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + + nodeTypes.put(toscaResourceName, toscaNodeType); + toscaNode.setNode_types(nodeTypes); + log.debug("finish convert node type for {}", component.getUniqueId()); + return Either.left(toscaNode); + } + + private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component, + List<ComponentInstance> componentInstances, + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, + Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes, + ToscaTopolgyTemplate topologyTemplate) { + + Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null; + log.debug("start convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>(); + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs(); + + Map<String, ToscaGroupTemplate> groupsMap = null; + for (ComponentInstance componentInstance : componentInstances) { + ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); + nodeTemplate.setType(componentInstance.getToscaComponentName()); + + Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor + .getOriginComponent(componentCache, componentInstance); + if (originComponentRes.isRight()) { + convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + break; + } + Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, + componentInstance, component.getComponentInstancesRelations(), nodeTemplate, + originComponentRes.left().value(), componentCache); + if (requirements.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + String instanceUniqueId = componentInstance.getUniqueId(); + log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); + + nodeTemplate = requirements.left().value(); + + Component originalComponent = componentCache.get(componentInstance.getActualComponentUid()); + + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){ + Component componentOfProxy = componentCache.get(componentInstance.getComponentUid()); + nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance)); + } else { + nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance)); + } + + Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor + .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); + if (capabilities.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); + + nodeTemplate = capabilities.left().value(); + Map<String, Object> props = new HashMap<>(); + + if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) { + // Adds the properties of parent component to map + addPropertiesOfParentComponent(dataTypes, componentInstance, originalComponent, props); + } + + if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { + addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, + instanceUniqueId, props); + } + + if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { + addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, + props); + } + if (props != null && !props.isEmpty()) { + nodeTemplate.setProperties(props); + } + + List<GroupInstance> groupInstances = componentInstance.getGroupInstances(); + if (groupInstances != null) { + if (groupsMap == null) { + groupsMap = new HashMap<>(); + } + for (GroupInstance groupInst : groupInstances) { + boolean addToTosca = true; + + List<String> artifacts = groupInst.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + groupsMap.put(groupInst.getName(), toscaGroup); + } + } + } + + nodeTemplates.put(componentInstance.getName(), nodeTemplate); + } + if (groupsMap != null) { + log.debug("instance groups added"); + topologyTemplate.addGroups(groupsMap); + } + if (component.getComponentType() == ComponentTypeEnum.SERVICE && MapUtils.isNotEmpty(((Service) component).getForwardingPaths())) { + log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabiltyRequirementConvertor, componentCache, toscaOperationFacade); + log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + } + if (convertNodeTemplatesRes == null) { + convertNodeTemplatesRes = Either.left(nodeTemplates); + } + log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + return convertNodeTemplatesRes; + } + + private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes, + Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance, + String instanceUniqueId, Map<String, Object> props) { + + List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId); + if (instanceInputsList != null) { + instanceInputsList.forEach(input -> { + + Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty() + ? input.getValue() : input.getDefaultValue(); + convertAndAddValue(dataTypes, componentInstance, props, input, supplier); + }); + } + } + + private void addPropertiesOfComponentInstance( + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, + Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId, + Map<String, Object> props) { + + if (!MapUtils.isEmpty(componentInstancesProperties)) { + componentInstancesProperties.get(instanceUniqueId).stream() + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getValue())); + } + } + + private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes, + ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) { + + List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties(); + if (!CollectionUtils.isEmpty(componentProperties)) { + componentProperties.stream() + // Filters out properties with empty default values + .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getDefaultValue())); + } + } + + /** + * @param dataTypes + * @param componentInstance + * @param props + * @param prop + * @param supplier + */ + private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, + Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) { + Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); + if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { + props.put(prop.getName(), convertedValue); + } + } + + private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, + ComponentInstance componentInstance, T input, Supplier<String> supplier) { + log.debug("Convert property or input value {} for instance {}", input.getName(), + componentInstance.getUniqueId()); + String propertyType = input.getType(); + String innerType = null; + if (input.getSchema() != null && input.getSchema().getProperty() != null) { + innerType = input.getSchema().getProperty().getType(); + } + return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); + } + + private ToscaGroupTemplate convertGroup(GroupDefinition group) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + Map<String, String> members = group.getMembers(); + if (members != null) + toscaGroup.setMembers(new ArrayList<String>(members.keySet())); + + Supplier<String> supplGroupType = () -> group.getType(); + Supplier<String> supplDescription = () -> group.getDescription(); + Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties(); + Supplier<String> supplgroupName = () -> group.getName(); + Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID(); + Supplier<String> supplGroupUUID = () -> group.getGroupUUID(); + Supplier<String> supplVersion = () -> group.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + + Supplier<String> supplGroupType = () -> groupInstance.getType(); + Supplier<String> supplDescription = () -> groupInstance.getDescription(); + Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance + .convertToGroupInstancesProperties(); + Supplier<String> supplgroupName = () -> groupInstance.getGroupName(); + Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID(); + Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID(); + Supplier<String> supplVersion = () -> groupInstance.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + + toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props, + Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID, + Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) { + boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; + toscaGroup.setType(groupType.get()); + + IToscaMetadata toscaMetadata; + if (!isVfModule) { + toscaMetadata = new ToscaMetadata(); + } else { + toscaMetadata = new VfModuleToscaMetadata(); + + Map<String, Object> properties = fillGroupProperties(props.get()); + if (!properties.containsKey(VF_MODULE_DESC_KEY) + || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { + properties.put(VF_MODULE_DESC_KEY, description.get()); + } + toscaGroup.setProperties(properties); + } + toscaMetadata.setName(groupName.get()); + toscaMetadata.setInvariantUUID(invariantUUID.get()); + toscaMetadata.setUUID(groupUUID.get()); + toscaMetadata.setVersion(version.get()); + return toscaMetadata; + } + + private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) { + Map<String, Object> properties = new HashMap<>(); + if (groupProps != null) { + for (GroupProperty gp : groupProps) { + if (gp.getName().equals(Constants.IS_BASE)) { + Boolean isBase = Boolean.parseBoolean(gp.getValue()); + String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; + properties.put(VF_MODULE_TYPE_KEY, type); + } else { + Object value = null; + String type = gp.getType(); + + switch (type) { + case "integer": + if (gp.getValue() != null) { + value = Integer.valueOf(gp.getValue()); + } + break; + case "boolean": + if (gp.getValue() != null) { + value = Boolean.valueOf(gp.getValue()); + } + break; + + default: + value = gp.getValue(); + break; + } + properties.put(gp.getName(), value); + } + } + } + return properties; + } + + private ToscaNodeType createNodeType(Component component) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + if (ModelConverter.isAtomicComponent(component)) { + if (((Resource) component).getDerivedFrom() != null) { + toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); + } + toscaNodeType.setDescription(component.getDescription()); // or + // name?? + } else { + String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() + : "tosca.nodes.Root"; + toscaNodeType.setDerived_from(derivedFrom); + } + return toscaNodeType; + } + + private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) { + + Map<String, ToscaNodeType> nodeTypesMap = null; + Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap); + + List<ComponentInstance> componetInstances = container.getComponentInstances(); + + if (componetInstances == null || componetInstances.isEmpty()) + return res; + Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>(); + List<ComponentInstance> proxyInst = componetInstances.stream() + .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) + .collect(Collectors.toList()); + if (proxyInst != null && !proxyInst.isEmpty()) { + for (ComponentInstance inst : proxyInst) { + serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); + } + } + + if (serviceProxyInstanceList.isEmpty()) + return res; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreComponentInstances(false); + Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade + .getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + serviceProxyOrigin.right().value()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + Component origComponent = serviceProxyOrigin.left().value(); + + nodeTypesMap = new HashMap<>(); + for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) { + Component serviceComponent = null; + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + Either<Component, StorageOperationStatus> service = toscaOperationFacade + .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); + if (service.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } else + serviceComponent = service.left().value(); + + ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue()); + nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); + } + + return Either.left(nodeTypesMap); + } + + private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent, + ComponentInstance instance) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + String derivedFrom = ((Resource) origComponent).getToscaResourceName(); + + toscaNodeType.setDerived_from(derivedFrom); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + } + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor + .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes); + + toscaNodeType.setCapabilities(capabilities); + + return toscaNodeType; + } + + private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, + ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, + ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) { + + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) { + log.debug("Failed to convert component instance requirements for the component instance {}. ", + componentInstance.getName()); + return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + if (!toscaRequirements.isEmpty()) { + nodeTypeTemplate.setRequirements(toscaRequirements); + } + log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); + return Either.left(nodeTypeTemplate); + } + + private boolean addRequirements(Component component, ComponentInstance componentInstance, + List<RequirementCapabilityRelDef> relations, Component originComponent, + List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) { + boolean result; + List<RequirementCapabilityRelDef> filteredRelations = relations.stream() + .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(filteredRelations)) { + result = true; + } else { + result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, + component.getComponentInstances(), rel, toscaRequirements, componentCache)).findFirst().isPresent(); + } + return result; + } + + private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, + List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel, + List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) { + + boolean result = true; + Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements(); + RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); + Either<Component, StorageOperationStatus> getOriginRes = null; + Optional<RequirementDefinition> reqOpt = null; + Component toOriginComponent = null; + Optional<CapabilityDefinition> cap = null; + + ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) + .findFirst().orElse(null); + if (toInstance == null) { + log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), + rel.getToNode()); + result = false; + } + if (result) { + reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId()); + if (!reqOpt.isPresent()) { + log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreCapabilities(false); + getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); + if (getOriginRes.isRight()) { + log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", + reqOpt.get().getName(), toInstance.getActualComponentUid()); + result = false; + } + } + if (result) { + toOriginComponent = getOriginRes.left().value(); + cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() + .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst(); + if (!cap.isPresent()) { + cap = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); + if(!cap.isPresent()){ + result = false; + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + } + } + if (result) { + result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), + reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache); + } + return result; + } + + private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) { + return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId())); + } + + private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { + Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst(); + if (!cap.isPresent()) { + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + return cap; + } + + private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) { + boolean result = true; + Either<String, Boolean> buildReqNameRes = null; + List<String> reducedPath = capability.getPath(); + if(capability.getOwnerId() !=null){ + reducedPath = capabiltyRequirementConvertor.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() ); + } + Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, + toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability()); + if (buildCapNameRes.isRight()) { + log.debug( + "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + result = false; + } + if (result) { + buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, fromOriginComponent, + requirement.getPath(), reqAndRelationshipPair.getRequirement()); + if (buildReqNameRes.isRight()) { + log.debug( + "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); + Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); + toscaRequirement.setNode(toInstance.getName()); + toscaRequirement.setCapability(buildCapNameRes.left().value()); + toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); + toscaRequirements.add(toscaReqMap); + } + return result; + } + + private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) { + for(List<RequirementDefinition> reqList: reqMap.values()){ + Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst(); + if(reqOpt.isPresent()){ + return reqOpt; + } + } + return Optional.empty(); + } + + /** + * Allows detecting the requirement belonging to the received relationship + * The detection logic is: A requirement belongs to a relationship IF 1.The + * name of the requirement equals to the "requirement" field of the + * relation; AND 2. In case of a non-atomic resource, OwnerId of the + * requirement equals to requirementOwnerId of the relation OR uniqueId of + * toInstance equals to capabilityOwnerId of the relation + */ + private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) { + if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())){ + log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}", + requirement.getName(), reqAndRelationshipPair.getRequirement()); + return false; + } + if (!ModelConverter.isAtomicComponent(originComponent)) + return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent); + return true; + } + + private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) { + return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())); + } + + private boolean isCvfc(Component component) { + if (component.getComponentType() != ComponentTypeEnum.RESOURCE) + return false; + return ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; + } + + private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, + SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) { + + Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); + Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor + .convertSubstitutionMappingCapabilities(componentCache, component); + if (toscaCapabilitiesRes.isRight()) { + result = Either.right(toscaCapabilitiesRes.right().value()); + log.error("Failed convert capabilities for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { + substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); + log.debug("Finish convert capabilities for the component {}. ", component.getName()); + } + log.debug("Finished to convert capabilities for the component {}. ", component.getName()); + return result; + } + + private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, + Map<String, DataTypeDefinition> dataTypes) { + Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, + dataTypes); + if (!toscaCapabilities.isEmpty()) { + nodeType.setCapabilities(toscaCapabilities); + } + log.debug("Finish convert Capabilities for node type"); + + return Either.left(nodeType); + } + + private static class CustomRepresenter extends Representer { + public CustomRepresenter() { + super(); + // null representer is exceptional and it is stored as an instance + // variable. + this.nullRepresenter = new RepresentNull(); + + } + + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, + Tag customTag) { + if (propertyValue == null) { + return null; + } else { + // skip not relevant for Tosca property + if ("dependencies".equals(property.getName())) { + return null; + } + NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + + return "_defaultp_".equals(property.getName()) + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; + } + } + + @Override + protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { + // remove the bean type from the output yaml (!! ...) + if (!classTags.containsKey(javaBean.getClass())) + addClassTag(javaBean.getClass(), Tag.MAP); + + return super.representJavaBean(properties, javaBean); + } + + private class RepresentNull implements Represent { + @Override + public Node representData(Object data) { + // possible values are here http://yaml.org/type/null.html + return representScalar(Tag.NULL, ""); + } + } + } + + private static class UnsortedPropertyUtils extends PropertyUtils { + @Override + protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) + throws IntrospectionException { + Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values(); + return new LinkedHashSet<>(fields); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java index 6b1895b6ec..49fd91cfed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java @@ -20,30 +20,30 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; + public class ToscaRepresentation { - private String mainYaml; - private List<Triple<String, String, Component>> dependencies; + private String mainYaml; + private List<Triple<String, String, Component>> dependencies; - public String getMainYaml() { - return mainYaml; - } + public String getMainYaml() { + return mainYaml; + } - public void setMainYaml(String mainYaml) { - this.mainYaml = mainYaml; - } + public void setMainYaml(String mainYaml) { + this.mainYaml = mainYaml; + } - public List<Triple<String, String, Component>> getDependencies() { - return dependencies; - } + public List<Triple<String, String, Component>> getDependencies() { + return dependencies; + } - public void setDependencies(List<Triple<String, String, Component>> dependancies) { - this.dependencies = dependancies; - } + public void setDependencies(List<Triple<String, String, Component>> dependancies) { + this.dependencies = dependancies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java index 0c54e7229e..8abaaf73f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java @@ -20,92 +20,88 @@ package org.openecomp.sdc.be.tosca; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Component; +import java.lang.reflect.Field; +import java.util.*; + public class ToscaUtils { - public static boolean isComplexVfc(Component component) { - if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (ResourceTypeEnum.CVFC == resourceType) { - return true; - } - } - return false; - } - - public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException { - Map<String, Object> map = new HashMap<>(); - List<Field> fields = new ArrayList<>(); - - fields = getAllFields(fields, clazz); - - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(objectToConvert)); - } - return map; - } - - public static List<Field> getAllFields(List<Field> fields, Class<?> type) { - fields.addAll(Arrays.asList(type.getDeclaredFields())); - - if (type.getSuperclass() != null) { - fields = getAllFields(fields, type.getSuperclass()); - } - return fields; - } - - public static class SubstituitionEntry{ - - private String fullName = ""; - private String sourceName = ""; - private String owner = ""; - - public SubstituitionEntry() {} - - public SubstituitionEntry(String fullName, String sourceName, String owner) { - if(fullName != null) - this.fullName = fullName; - if(sourceName != null) - this.sourceName = sourceName; - if(owner != null) - this.owner = owner; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getSourceName() { - return sourceName; - } - - public void setSourceName(String sourceName) { - this.sourceName = sourceName; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - } - + public static boolean isComplexVfc(Component component) { + if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (ResourceTypeEnum.CVFC == resourceType) { + return true; + } + } + return false; + } + + public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException { + Map<String, Object> map = new HashMap<>(); + List<Field> fields = new ArrayList<>(); + + fields = getAllFields(fields, clazz); + + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(objectToConvert)); + } + return map; + } + + public static List<Field> getAllFields(List<Field> fields, Class<?> type) { + fields.addAll(Arrays.asList(type.getDeclaredFields())); + + if (type.getSuperclass() != null) { + fields = getAllFields(fields, type.getSuperclass()); + } + return fields; + } + + public static class SubstituitionEntry{ + + private String fullName = ""; + private String sourceName = ""; + private String owner = ""; + + public SubstituitionEntry() {} + + public SubstituitionEntry(String fullName, String sourceName, String owner) { + if(fullName != null) + this.fullName = fullName; + if(sourceName != null) + this.sourceName = sourceName; + if(owner != null) + this.owner = owner; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java index 0c586c7043..f1a7dcb9e5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java @@ -21,23 +21,23 @@ package org.openecomp.sdc.be.tosca.model; public class EntrySchema { - private String type; - private String description; + private String type; + private String description; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java index 70b05b8158..1bb865f562 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java @@ -22,13 +22,13 @@ package org.openecomp.sdc.be.tosca.model; public interface IToscaMetadata { - public void setName(String name); + public void setName(String name); - public void setInvariantUUID(String invariantUUID); + public void setInvariantUUID(String invariantUUID); - public void setUUID(String uUID); + public void setUUID(String uUID); - public void setVersion(String version); - - public void setCustomizationUUID(String customizationUUID); + public void setVersion(String version); + + public void setCustomizationUUID(String customizationUUID); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java index 5dc8ddee2a..bbbb303900 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java @@ -23,36 +23,36 @@ package org.openecomp.sdc.be.tosca.model; import java.util.Map; public class SubstitutionMapping { - private String node_type; - private Map<String, String[]> capabilities; - private Map<String, String[]> requirements; - - public SubstitutionMapping() { - super(); - // TODO Auto-generated constructor stub - } - - public String getNode_type() { - return node_type; - } - - public void setNode_type(String node_type) { - this.node_type = node_type; - } - - public Map<String, String[]> getCapabilities() { - return capabilities; - } - - public void setCapabilities(Map<String, String[]> capabilities) { - this.capabilities = capabilities; - } - - public Map<String, String[]> getRequirements() { - return requirements; - } - - public void setRequirements(Map<String, String[]> requirements) { - this.requirements = requirements; - } + private String node_type; + private Map<String, String[]> capabilities; + private Map<String, String[]> requirements; + + public SubstitutionMapping() { + super(); + // TODO Auto-generated constructor stub + } + + public String getNode_type() { + return node_type; + } + + public void setNode_type(String node_type) { + this.node_type = node_type; + } + + public Map<String, String[]> getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map<String, String[]> capabilities) { + this.capabilities = capabilities; + } + + public Map<String, String[]> getRequirements() { + return requirements; + } + + public void setRequirements(Map<String, String[]> requirements) { + this.requirements = requirements; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java index 2688e5e6b3..d26fd0447c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java @@ -25,56 +25,56 @@ import java.util.Map; public class ToscaCapability { - private String type; - private String description; + private String type; + private String description; - private List<Object> occurrences; + private List<Object> occurrences; - private List<String> valid_source_types; + private List<String> valid_source_types; - private Map<String, ToscaProperty> properties; + private Map<String, ToscaProperty> properties; - public List<String> getValid_source_types() { - return valid_source_types; - } + public List<String> getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List<String> valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List<String> valid_source_types) { + this.valid_source_types = valid_source_types; + } - public ToscaCapability() { - } + public ToscaCapability() { + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public List<Object> getOccurrences() { - return occurrences; - } + public List<Object> getOccurrences() { + return occurrences; + } - public void setOccurrences(List<Object> occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List<Object> occurrences) { + this.occurrences = occurrences; + } - public Map<String, ToscaProperty> getProperties() { - return properties; - } + public Map<String, ToscaProperty> getProperties() { + return properties; + } - public void setProperties(Map<String, ToscaProperty> properties) { - this.properties = properties; - } + public void setProperties(Map<String, ToscaProperty> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java index b91cffa5be..2c5e095b8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java @@ -24,46 +24,46 @@ import java.util.List; import java.util.Map; public class ToscaGroupTemplate { - private String type; - List<String> members; - private IToscaMetadata metadata; - private Map<String, Object> properties; + private String type; + List<String> members; + private IToscaMetadata metadata; + private Map<String, Object> properties; - public ToscaGroupTemplate() { - super(); + public ToscaGroupTemplate() { + super(); - } + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public List<String> getMembers() { - return members; - } + public List<String> getMembers() { + return members; + } - public void setMembers(List<String> members) { - this.members = members; - } + public void setMembers(List<String> members) { + this.members = members; + } - public IToscaMetadata getMetadata() { - return metadata; - } + public IToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(IToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(IToscaMetadata metadata) { + this.metadata = metadata; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java index 4f91e211cc..69907beaec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java @@ -21,200 +21,200 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaMetadata implements IToscaMetadata { - private String invariantUUID; - private String UUID; - private String customizationUUID; - private String version; - private String name; - private String description; - private String type; - private String category; - private String subcategory; - private String resourceVendor; - private String resourceVendorRelease; - private String resourceVendorModelNumber; - private String serviceType; - private String serviceRole; - private Boolean serviceEcompNaming; - private Boolean ecompGeneratedNaming; - private String namingPolicy; - private String sourceModelInvariant; - private String environmentContext; - private String sourceModelName; - private String sourceModelUuid; - - - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getInvariantUUID() { - return invariantUUID; - } - - @Override - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - public String getUUID() { - return UUID; - } - - @Override - public void setUUID(String uUID) { - UUID = uUID; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } - - public String getResourceVendor() { - return resourceVendor; - } - - public void setResourceVendor(String resourceVendor) { - this.resourceVendor = resourceVendor; - } - - public String getResourceVendorRelease() { - return resourceVendorRelease; - } - - public void setResourceVendorRelease(String resourceVendorRelease) { - this.resourceVendorRelease = resourceVendorRelease; - } - - public String getResourceVendorModelNumber() { - return resourceVendorModelNumber; - } - - public void setResourceVendorModelNumber(String resourceVendorModelNumber) { - this.resourceVendorModelNumber = resourceVendorModelNumber; - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceRole() { - return serviceRole; - } - - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; - } - - public Boolean isEcompGeneratedNaming() { - return ecompGeneratedNaming; - } - - public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { - this.ecompGeneratedNaming = ecompGeneratedNaming; - } - - public String isNamingPolicy() { - return namingPolicy; - } - - public void setNamingPolicy(String namingPolicy) { - this.namingPolicy = namingPolicy; - } - - public Boolean getServiceEcompNaming() { - return serviceEcompNaming; - } - - public void setServiceEcompNaming(Boolean serviceEcompNaming) { - this.serviceEcompNaming = serviceEcompNaming; - } - - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - public String getCustomizationUUID() { - return customizationUUID; - } - - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public String getSourceModelInvariant() { - return sourceModelInvariant; - } - - public void setSourceModelInvariant(String sourceModelInvariant) { - this.sourceModelInvariant = sourceModelInvariant; - } - - public String getSourceModelName() { - return sourceModelName; - } - - public void setSourceModelName(String sourceModelName) { - this.sourceModelName = sourceModelName; - } - - public String getSourceModelUuid() { - return sourceModelUuid; - } - - public void setSourceModelUuid(String sourceModelUuid) { - this.sourceModelUuid = sourceModelUuid; - } - - - - public String getEnvironmentContext() { - return environmentContext; - } - - public void setEnvironmentContext(String environmentContext) { - this.environmentContext = environmentContext; - } + private String invariantUUID; + private String UUID; + private String customizationUUID; + private String version; + private String name; + private String description; + private String type; + private String category; + private String subcategory; + private String resourceVendor; + private String resourceVendorRelease; + private String resourceVendorModelNumber; + private String serviceType; + private String serviceRole; + private Boolean serviceEcompNaming; + private Boolean ecompGeneratedNaming; + private String namingPolicy; + private String sourceModelInvariant; + private String environmentContext; + private String sourceModelName; + private String sourceModelUuid; + + + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + @Override + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getUUID() { + return UUID; + } + + @Override + public void setUUID(String uUID) { + UUID = uUID; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + public String getResourceVendor() { + return resourceVendor; + } + + public void setResourceVendor(String resourceVendor) { + this.resourceVendor = resourceVendor; + } + + public String getResourceVendorRelease() { + return resourceVendorRelease; + } + + public void setResourceVendorRelease(String resourceVendorRelease) { + this.resourceVendorRelease = resourceVendorRelease; + } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public Boolean isEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String isNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getServiceEcompNaming() { + return serviceEcompNaming; + } + + public void setServiceEcompNaming(Boolean serviceEcompNaming) { + this.serviceEcompNaming = serviceEcompNaming; + } + + public String getVersion() { + return version; + } + + @Override + public void setVersion(String version) { + this.version = version; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public String getSourceModelInvariant() { + return sourceModelInvariant; + } + + public void setSourceModelInvariant(String sourceModelInvariant) { + this.sourceModelInvariant = sourceModelInvariant; + } + + public String getSourceModelName() { + return sourceModelName; + } + + public void setSourceModelName(String sourceModelName) { + this.sourceModelName = sourceModelName; + } + + public String getSourceModelUuid() { + return sourceModelUuid; + } + + public void setSourceModelUuid(String sourceModelUuid) { + this.sourceModelUuid = sourceModelUuid; + } + + + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java index b2d7ef5ab6..c27944e8ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java @@ -24,50 +24,58 @@ import java.util.List; import java.util.Map; public class ToscaNodeTemplate { - private String type; - private ToscaMetadata metadata; - private Map<String, Object> properties; - private List<Map<String, ToscaTemplateRequirement>> requirements; - private Map<String, ToscaTemplateCapability> capabilities; + private String type; + private ToscaMetadata metadata; + private String description; + private Map<String, Object> properties; + private List<Map<String, ToscaTemplateRequirement>> requirements; + private Map<String, ToscaTemplateCapability> capabilities; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } - public List<Map<String, ToscaTemplateRequirement>> getRequirements() { - return requirements; - } + public List<Map<String, ToscaTemplateRequirement>> getRequirements() { + return requirements; + } - public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) { - this.requirements = requirements; - } + public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) { + this.requirements = requirements; + } - public Map<String, ToscaTemplateCapability> getCapabilities() { - return capabilities; - } + public Map<String, ToscaTemplateCapability> getCapabilities() { + return capabilities; + } - public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) { + this.capabilities = capabilities; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java index df9070f49c..4f56cc3bef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java @@ -24,64 +24,64 @@ import java.util.List; import java.util.Map; public class ToscaNodeType { - public ToscaNodeType() { - } + public ToscaNodeType() { + } - private ToscaMetadata metadata; - private String derived_from; - private String description; + private ToscaMetadata metadata; + private String derived_from; + private String description; - private Map<String, ToscaProperty> properties; - private Map<String, ToscaCapability> capabilities; + private Map<String, ToscaProperty> properties; + private Map<String, ToscaCapability> capabilities; - private List<Map<String, ToscaRequirement>> requirements; + private List<Map<String, ToscaRequirement>> requirements; - public Map<String, ToscaProperty> getProperties() { - return properties; - } + public Map<String, ToscaProperty> getProperties() { + return properties; + } - public void setProperties(Map<String, ToscaProperty> properties) { - this.properties = properties; - } + public void setProperties(Map<String, ToscaProperty> properties) { + this.properties = properties; + } - public Map<String, ToscaCapability> getCapabilities() { - return capabilities; - } + public Map<String, ToscaCapability> getCapabilities() { + return capabilities; + } - public void setCapabilities(Map<String, ToscaCapability> capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map<String, ToscaCapability> capabilities) { + this.capabilities = capabilities; + } - public List<Map<String, ToscaRequirement>> getRequirements() { - return requirements; - } + public List<Map<String, ToscaRequirement>> getRequirements() { + return requirements; + } - public void setRequirements(List<Map<String, ToscaRequirement>> requirements) { - this.requirements = requirements; - } + public void setRequirements(List<Map<String, ToscaRequirement>> requirements) { + this.requirements = requirements; + } - public String getDerived_from() { - return derived_from; - } + public String getDerived_from() { + return derived_from; + } - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } + public void setDerived_from(String derived_from) { + this.derived_from = derived_from; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java index 8b5c60b1d4..e1ac69fbe0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java @@ -22,62 +22,62 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaProperty { - private String type; - private Object _defaultp_; - private String description; - private Boolean required; - private EntrySchema entry_schema; - private String status; - - public EntrySchema getEntry_schema() { - return entry_schema; - } - - public void setEntry_schema(EntrySchema entry_schema) { - this.entry_schema = entry_schema; - } - - public ToscaProperty() { - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Object getDefaultp() { - return _defaultp_; - } - - public void setDefaultp(Object defaultp) { - this._defaultp_ = defaultp; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Boolean getRequired() { - return required; - } - - public void setRequired(Boolean required) { - this.required = required; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } + private String type; + private Object _defaultp_; + private String description; + private Boolean required; + private EntrySchema entry_schema; + private String status; + + public EntrySchema getEntry_schema() { + return entry_schema; + } + + public void setEntry_schema(EntrySchema entry_schema) { + this.entry_schema = entry_schema; + } + + public ToscaProperty() { + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Object getDefaultp() { + return _defaultp_; + } + + public void setDefaultp(Object defaultp) { + this._defaultp_ = defaultp; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java index 21fdc9f722..35d5c4e6e1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java @@ -25,21 +25,21 @@ import java.util.Map; public class ToscaRequirement extends ToscaTemplateRequirement { - private List<Object> occurrences; + private List<Object> occurrences; - public ToscaRequirement() { - } + public ToscaRequirement() { + } - public List<Object> getOccurrences() { - return occurrences; - } + public List<Object> getOccurrences() { + return occurrences; + } - public void setOccurrences(List<Object> occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List<Object> occurrences) { + this.occurrences = occurrences; + } - public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { - return super.toMap(); - } + public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { + return super.toMap(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java index e80d52167c..387238206c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java @@ -20,71 +20,71 @@ package org.openecomp.sdc.be.tosca.model; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; +import java.util.Map; + public class ToscaTemplate { - private String tosca_definitions_version; - private ToscaMetadata metadata; - private List<Map<String, Map<String, String>>> imports; - private Map<String, ToscaNodeType> node_types; - private ToscaTopolgyTemplate topology_template; + private String tosca_definitions_version; + private ToscaMetadata metadata; + private List<Map<String, Map<String, String>>> imports; + private Map<String, ToscaNodeType> node_types; + private ToscaTopolgyTemplate topology_template; - private List<Triple<String, String, Component>> dependencies; + private List<Triple<String, String, Component>> dependencies; - public ToscaTemplate(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public ToscaTemplate(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public Map<String, ToscaNodeType> getNode_types() { - return node_types; - } + public Map<String, ToscaNodeType> getNode_types() { + return node_types; + } - public void setNode_types(Map<String, ToscaNodeType> node_types) { - this.node_types = node_types; - } + public void setNode_types(Map<String, ToscaNodeType> node_types) { + this.node_types = node_types; + } - public List<Map<String, Map<String, String>>> getImports() { - return imports; - } + public List<Map<String, Map<String, String>>> getImports() { + return imports; + } - public void setImports(List<Map<String, Map<String, String>>> imports) { - this.imports = imports; - } + public void setImports(List<Map<String, Map<String, String>>> imports) { + this.imports = imports; + } - public String getTosca_definitions_version() { - return tosca_definitions_version; - } + public String getTosca_definitions_version() { + return tosca_definitions_version; + } - public void setTosca_definitions_version(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } - public ToscaTopolgyTemplate getTopology_template() { - return topology_template; - } + public ToscaTopolgyTemplate getTopology_template() { + return topology_template; + } - public void setTopology_template(ToscaTopolgyTemplate topology_template) { - this.topology_template = topology_template; - } + public void setTopology_template(ToscaTopolgyTemplate topology_template) { + this.topology_template = topology_template; + } - public List<Triple<String, String, Component>> getDependencies() { - return dependencies; - } + public List<Triple<String, String, Component>> getDependencies() { + return dependencies; + } - public void setDependencies(List<Triple<String, String, Component>> dependencies) { - this.dependencies = dependencies; - } + public void setDependencies(List<Triple<String, String, Component>> dependencies) { + this.dependencies = dependencies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java index 9adb9edfe1..68341079c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java @@ -24,23 +24,23 @@ import java.util.List; import java.util.Map; public class ToscaTemplateCapability { - private List<String> valid_source_types; - private Map<String, Object> properties; + private List<String> valid_source_types; + private Map<String, Object> properties; - public List<String> getValid_source_types() { - return valid_source_types; - } + public List<String> getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List<String> valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List<String> valid_source_types) { + this.valid_source_types = valid_source_types; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java index 71bae81f9c..7a77c4f47c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java @@ -25,44 +25,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTemplateRequirement { - private String capability; - private String node; - private String relationship; + private String capability; + private String node; + private String relationship; - public ToscaTemplateRequirement() { - } + public ToscaTemplateRequirement() { + } - public String getCapability() { - return capability; - } + public String getCapability() { + return capability; + } - public void setCapability(String capability) { - this.capability = capability; - } + public void setCapability(String capability) { + this.capability = capability; + } - public String getNode() { - return node; - } + public String getNode() { + return node; + } - public void setNode(String node) { - this.node = node; - } + public void setNode(String node) { + this.node = node; + } - public String getRelationship() { - return relationship; - } + public String getRelationship() { + return relationship; + } - public void setRelationship(String relationship) { - this.relationship = relationship; - } + public void setRelationship(String relationship) { + this.relationship = relationship; + } - public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { - Map<String, Object> map = new HashMap<>(); - Field[] fields = this.getClass().getDeclaredFields(); - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(this)); - } - return map; - } + public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { + Map<String, Object> map = new HashMap<>(); + Field[] fields = this.getClass().getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(this)); + } + return map; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java index df285c6ad9..8ef32cb06f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java @@ -24,44 +24,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTopolgyTemplate { - private Map<String, ToscaProperty> inputs; - private Map<String, ToscaNodeTemplate> node_templates; - private Map<String, ToscaGroupTemplate> groups; - private SubstitutionMapping substitution_mappings; + private Map<String, ToscaProperty> inputs; + private Map<String, ToscaNodeTemplate> node_templates; + private Map<String, ToscaGroupTemplate> groups; + private SubstitutionMapping substitution_mappings; - public Map<String, ToscaNodeTemplate> getNode_templates() { - return node_templates; - } + public Map<String, ToscaNodeTemplate> getNode_templates() { + return node_templates; + } - public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) { - this.node_templates = node_templates; - } + public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) { + this.node_templates = node_templates; + } - public Map<String, ToscaGroupTemplate> getGroups() { - return groups; - } + public Map<String, ToscaGroupTemplate> getGroups() { + return groups; + } - public void addGroups(Map<String, ToscaGroupTemplate> groups) { - if ( this.groups == null ){ - this.groups = new HashMap<>(); - } - this.groups.putAll(groups); - } + public void addGroups(Map<String, ToscaGroupTemplate> groups) { + if ( this.groups == null ){ + this.groups = new HashMap<>(); + } + this.groups.putAll(groups); + } - public SubstitutionMapping getSubstitution_mappings() { - return substitution_mappings; - } + public SubstitutionMapping getSubstitution_mappings() { + return substitution_mappings; + } - public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { - this.substitution_mappings = substitution_mapping; - } + public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { + this.substitution_mappings = substitution_mapping; + } - public Map<String, ToscaProperty> getInputs() { - return inputs; - } + public Map<String, ToscaProperty> getInputs() { + return inputs; + } - public void setInputs(Map<String, ToscaProperty> inputs) { - this.inputs = inputs; - } + public void setInputs(Map<String, ToscaProperty> inputs) { + this.inputs = inputs; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java index 26ce118a1a..198e233fde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java @@ -22,54 +22,54 @@ package org.openecomp.sdc.be.tosca.model; public class VfModuleToscaMetadata implements IToscaMetadata { - private String vfModuleModelName; - private String vfModuleModelInvariantUUID; - private String vfModuleModelUUID; - private String vfModuleModelVersion; - private String vfModuleModelCustomizationUUID; + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelUUID; + private String vfModuleModelVersion; + private String vfModuleModelCustomizationUUID; - @Override - public void setName(String name) { - vfModuleModelName = name; - } + @Override + public void setName(String name) { + vfModuleModelName = name; + } - @Override - public void setInvariantUUID(String invariantUUID) { - vfModuleModelInvariantUUID = invariantUUID; - } + @Override + public void setInvariantUUID(String invariantUUID) { + vfModuleModelInvariantUUID = invariantUUID; + } - @Override - public void setUUID(String uUID) { - vfModuleModelUUID = uUID; - } + @Override + public void setUUID(String uUID) { + vfModuleModelUUID = uUID; + } - @Override - public void setVersion(String version) { - vfModuleModelVersion = version; - } + @Override + public void setVersion(String version) { + vfModuleModelVersion = version; + } - public String getVfModuleModelName() { - return vfModuleModelName; - } + public String getVfModuleModelName() { + return vfModuleModelName; + } - public String getVfModuleModelInvariantUUID() { - return vfModuleModelInvariantUUID; - } + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } - public String getVfModuleModelUUID() { - return vfModuleModelUUID; - } + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } - public String getVfModuleModelVersion() { - return vfModuleModelVersion; - } + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } - public String getVfModuleModelCustomizationUUID() { - return vfModuleModelCustomizationUUID; - } + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } - public void setCustomizationUUID(String customizationUUID) { - this.vfModuleModelCustomizationUUID = customizationUUID; - } + public void setCustomizationUUID(String customizationUUID) { + this.vfModuleModelCustomizationUUID = customizationUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java new file mode 100644 index 0000000000..c4905d005e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.be.tosca.utils; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; + +import java.util.*; + +/** + * @author KATYR + * @since November 19, 2017 + */ + +public class ForwardingPathToscaUtil { + public static final String FORWARDS_TO_TOSCA_NAME = + "org.openecomp.relationships.ForwardsTo"; + public static final String PROTOCOL = "protocol"; + public static final String PORTS_RANGE = "target_range"; + public static final String FORWARDER = "forwarder"; + + public static void addForwardingPaths(Service service, Map<String, ToscaNodeTemplate> + nodeTemplates, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) { + for (String forwardingPathName : service.getForwardingPaths().keySet()) { + ToscaNodeTemplate forwardingPathNodeTemplate = + new ToscaNodeTemplate(); + final ForwardingPathDataDefinition path = + service.getForwardingPaths().get(forwardingPathName); + forwardingPathNodeTemplate.setType(path.getToscaResourceName()); + + if (Objects.nonNull(path.getDescription())) { + forwardingPathNodeTemplate.setDescription(path + .getDescription()); + } + Map<String, Object> props = new HashMap<>(); + if (Objects.nonNull(path.getDestinationPortNumber())) { + props.put(PORTS_RANGE, Collections.singletonList(path.getDestinationPortNumber())); + } + if (Objects.nonNull(path.getProtocol())) { + props.put(PROTOCOL, path.getProtocol()); + } + if (MapUtils.isNotEmpty(props)) { + forwardingPathNodeTemplate.setProperties(props); + } + + final List<ForwardingPathElementDataDefinition> pathElements = + path.getPathElements() + .getListToscaDataDefinition(); + forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements, + service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade)); + + nodeTemplates.put(path.getName(), forwardingPathNodeTemplate); + } + + } + + private static List<Map<String, ToscaTemplateRequirement>> convertPathElementsToRequirements( + List<ForwardingPathElementDataDefinition> pathElements, Service service, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents,ToscaOperationFacade toscaOperationFacade) { + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + for (int i = 0; i <= pathElements.size() -1 ; i++) { + final ForwardingPathElementDataDefinition element = pathElements.get(i); + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element.getFromNode()))); + if ( i == pathElements.size() -1) { + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element + .getToNode()))); + } + } + return toscaRequirements; + + } + + private static String fetchNodeName(Service service, String nodeId) { + if (service.getComponentInstanceById(nodeId).isPresent()) { + return service.getComponentInstanceById(nodeId).get().getName(); + } else { + return ""; + } + } + + + private static Map<String, ToscaTemplateRequirement> handleSingleReq( + String fromCP, String fromNode) { + Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); + ToscaTemplateRequirement firstReq = new ToscaTemplateRequirement(); + firstReq.setRelationship(FORWARDS_TO_TOSCA_NAME); //todo + firstReq.setCapability(fromCP); + firstReq.setNode(fromNode); + toscaReqMap.put(FORWARDER, firstReq); + + return toscaReqMap; + } + + /** + * @todo handle errors. + */ + private static String fetchCPName(Service service, String nodeID, String cpName, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) { + Optional<ComponentInstance> componentInstance = service.getComponentInstanceById(nodeID); + ComponentInstance componentInstanceVal = componentInstance.get(); + String name = componentInstanceVal.getNormalizedName(); + Component component = originComponents.get(componentInstanceVal.getComponentUid()); + if(componentInstanceVal.getIsProxy()){ + component = originComponents.get(componentInstanceVal.getSourceModelUid()); + if (component == null) { + component = toscaOperationFacade.getToscaFullElement(componentInstanceVal.getSourceModelUid()).left().value(); + } + + } + CapabilityDefinition capability = componentInstanceVal.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(cpName)).findAny().get(); + List<String> path = capability.getPath(); + List<String> reducedPath = new ArrayList<>(path); + reducedPath.remove(reducedPath.size() - 1); + Either<String, Boolean> stringBooleanEither = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, component, reducedPath, capability.getName()); + return name + "." + stringBooleanEither.left().value(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java index 6bec3fa938..ee454d72f3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java @@ -20,15 +20,13 @@ package org.openecomp.sdc.be.user; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.List; /** * @@ -36,17 +34,17 @@ import fj.data.Either; * */ public interface IUserBusinessLogic { - public Either<User, ActionStatus> getUser(String userId, boolean inTransaction); + public Either<User, ActionStatus> getUser(String userId, boolean inTransaction); - public Either<User, ResponseFormat> createUser(User modifier, User newUser); + public Either<User, ResponseFormat> createUser(User modifier, User newUser); - public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole); + public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole); - public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context); + public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context); - public Either<List<User>, ResponseFormat> getUsersList(String userId, List<String> roles, String rolesStr); + public Either<List<User>, ResponseFormat> getUsersList(String userId, List<String> roles, String rolesStr); - public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive); + public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive); - public Either<User, ResponseFormat> authorize(User authUser); + public Either<User, ResponseFormat> authorize(User authUser); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java index ab58ea7bf0..9397f6d93b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java @@ -25,5 +25,5 @@ package org.openecomp.sdc.be.user; * which may result in ecompRole id change */ public enum Role { - ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST + ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java index ffc5e4f947..f5b33beb7e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java @@ -22,6 +22,6 @@ package org.openecomp.sdc.be.user; public enum UserAdminAction { - ADD_USER, UPDATE_USER, DELET_USER + ADD_USER, UPDATE_USER, DELET_USER } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java index 796b3a78c0..589fdd8de4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java @@ -25,44 +25,44 @@ import java.util.regex.Pattern; public class UserAdminValidator { - private Pattern emailPat; - private Pattern userIdPat; - private Matcher matcher; + private Pattern emailPat; + private Pattern userIdPat; + private Matcher matcher; - private static UserAdminValidator userAdminValidator = null; + private static UserAdminValidator userAdminValidator = null; - public static synchronized UserAdminValidator getInstance() { - if (userAdminValidator == null) { - userAdminValidator = new UserAdminValidator(); - } - return userAdminValidator; - } + public static synchronized UserAdminValidator getInstance() { + if (userAdminValidator == null) { + userAdminValidator = new UserAdminValidator(); + } + return userAdminValidator; + } - private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - private static final String USER_ID_PATTERN = "\\w{1,25}"; + private static final String USER_ID_PATTERN = "\\w{1,25}"; - private UserAdminValidator() { - emailPat = Pattern.compile(EMAIL_PATTERN); - userIdPat = Pattern.compile(USER_ID_PATTERN); - } + private UserAdminValidator() { + emailPat = Pattern.compile(EMAIL_PATTERN); + userIdPat = Pattern.compile(USER_ID_PATTERN); + } - public boolean validateEmail(final String hex) { - matcher = emailPat.matcher(hex); - return matcher.matches(); - } + public boolean validateEmail(final String hex) { + matcher = emailPat.matcher(hex); + return matcher.matches(); + } - public boolean validateUserId(String userId) { - matcher = userIdPat.matcher(userId); - return matcher.matches(); - } + public boolean validateUserId(String userId) { + matcher = userIdPat.matcher(userId); + return matcher.matches(); + } - public boolean validateRole(String role) { - for (Role r : Role.values()) { - if (r.name().equals(role)) { - return true; - } - } - return false; - } + public boolean validateRole(String role) { + for (Role r : Role.values()) { + if (r.name().equals(role)) { + return true; + } + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index 90318a6259..324019a5e8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.user; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,590 +42,592 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component("userBusinessLogic") public class UserBusinessLogic implements IUserBusinessLogic { - private static Logger log = LoggerFactory.getLogger(UserBusinessLogic.class.getName()); - private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance(); - - @Resource - private IUserAdminOperation userAdminOperation; - @Resource - private ComponentsUtils componentsUtils; - @Autowired - private TitanGenericDao titanDao; - - @Override - public Either<User, ActionStatus> getUser(String userId, boolean inTransaction) { - return userAdminOperation.getUserData(userId, inTransaction); - } - - @Override - public Either<User, ResponseFormat> createUser(User modifier, User newUser) { - - ResponseFormat responseFormat; - String modifierUserId = modifier.getUserId(); - - if (modifierUserId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("createUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("createUser method - user is not admin = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - // verify user not exist - User userFromDb = new User(); - // boolean isUserAlreadyExist = false; - Either<User, ActionStatus> eitherUserInDB = getUser(newUser.getUserId(), false); - if (eitherUserInDB.isRight()) { - ActionStatus status = eitherUserInDB.right().value(); - if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) { - responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } else {// User exist in DB - userFromDb = eitherUserInDB.left().value(); - // isUserAlreadyExist = true; - if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) { - responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId()); - log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } - - newUser.setStatus(UserStatusEnum.ACTIVE); - - // validate Email - if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) { - log.debug("createUser method - user has invalid email = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - // validate Role - if (newUser.getRole() == null || newUser.getRole().length() == 0) { - newUser.setRole(Role.DESIGNER.name()); - } else { - if (!userAdminValidator.validateRole(newUser.getRole())) { - log.debug("createUser method - user has invalid role = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } - - // handle last login if user is import - if (newUser.getLastLoginTime() == null) { - newUser.setLastLoginTime(0L); - } - - Either<User, StorageOperationStatus> addOrUpdateUserReq; - - if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user - // exist - // with - // inactive - // state - // - - // update - // user - // data - newUser.setLastLoginTime(0L); - addOrUpdateUserReq = userAdminOperation.updateUserData(newUser); - - } else { // user not exist - create new user - - if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) { - log.debug("createUser method - user has invalid userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - addOrUpdateUserReq = userAdminOperation.saveUserData(newUser); - } - - if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) { - log.debug("createUser method - failed to create user"); - Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value()))); - } - log.debug("createUser method - user created"); - User createdUser = addOrUpdateUserReq.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER); - return Either.left(createdUser); - } - - @Override - public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole) { - - ResponseFormat responseFormat; - String modifierUserId = modifier.getUserId(); - - if (modifierUserId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("updateUserRole method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - if (modifier.getUserId().equals(userIdToUpdate)) { - log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false); - if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) { - log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - if (!userAdminValidator.validateRole(userRole)) { - log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - User newUser = new User(); - newUser.setRole(userRole); - newUser.setUserId(userIdToUpdate); - User userToUpdate = userToUpdateReq.left().value(); - // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in - // comment until admin will be able to do do check-in/check-out from the - // UI - - Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); - if (userPendingTasksReq.isRight()) { - log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); - } - - List<Edge> userPendingTasks = userPendingTasksReq.left().value(); - if (!userPendingTasks.isEmpty()) { - log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); - - String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); - String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); - handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - // } - Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(newUser); - - if (updateUserReq.isRight() || updateUserReq.left().value() == null) { - log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value()))); - } - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - User updatedUser = updateUserReq.left().value(); - handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.left(updatedUser); - } - - @Override - public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context) { - Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null); - - if (response.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value()); - return Either.right(responseFormat); - } - return Either.left(response.left().value()); - } - - @Override - public Either<List<User>, ResponseFormat> getUsersList(String modifierAttId, List<String> roles, String rolesStr) { - ResponseFormat responseFormat; - User user = new User(); - if (modifierAttId == null) { - user.setUserId("UNKNOWN"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - Either<User, ActionStatus> userResult = getUser(modifierAttId, false); - if (userResult.isRight()) { - user.setUserId(modifierAttId); - if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); - } - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Get users per roles", modifierAttId); - BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId); - - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - user = userResult.left().value(); - Either<List<User>, ResponseFormat> getResponse = null; - List<User> resultList = new ArrayList<>(); - if (roles != null && !roles.isEmpty()) { - for (String role : roles) { - if (!userAdminValidator.validateRole(role)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - getResponse = getUsersPerRole(role, user, rolesStr); - resultList.addAll(getResponse.left().value()); - } - } else { - rolesStr = "All"; - getResponse = getUsersPerRole(null, user, rolesStr); - resultList.addAll(getResponse.left().value()); - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.left(resultList); - } - - private Either<List<User>, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) { - ResponseFormat responseFormat; - Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name()); - if (response.isRight()) { - responseFormat = componentsUtils.getResponseFormat(response.right().value()); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - return Either.left(response.left().value()); - } - - private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) { - componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat); - } - - private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) { - componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat); - } - - private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) { - componentsUtils.auditUserAccess(actionName, user, responseFormat); - } - - @Override - public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive) { - - ResponseFormat responseFormat; - String userId = modifier.getUserId(); - - if (userId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("deActivateUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> eitherCreator = getUser(userId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - if (modifier.getUserId().equals(userUniuqeIdToDeactive)) { - log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false); - if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) { - log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive)); - } - - User userToDeactivate = getUserToDeleteResponse.left().value(); - if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) { - log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); - if (userPendingTasksReq.isRight()) { - log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); - } - - List<Edge> userPendingTasks = userPendingTasksReq.left().value(); - if (userPendingTasks.size() > 0) { - log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); - - String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); - String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); - handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either<User, StorageOperationStatus> deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate); - if (deactivateUserReq.isRight()) { - log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value()))); - } - User deactivateUser = deactivateUserReq.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.left(deactivateUser); - } - - @Override - public Either<User, ResponseFormat> authorize(User authUser) { - - ResponseFormat responseFormat; - - String userId = authUser.getUserId(); - - if (userId == null) { - authUser.setUserId("UNKNOWN"); - log.debug("deActivateUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> eitherCreator = getUser(userId, false); - if (eitherCreator.isRight()) { - if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } else { - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser)); - } - } else { - if (eitherCreator.left().value() == null) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - User user = eitherCreator.left().value(); - - String firstName = authUser.getFirstName(); - if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { - user.setFirstName(firstName); - } - - String lastName = authUser.getLastName(); - if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { - user.setLastName(lastName); - } - - String email = authUser.getEmail(); - if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { - user.setEmail(email); - } - - // last login time stamp handle - user.setLastLoginTime(); - - Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user); - - if (updateUserReq.isRight()) { - responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); - handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); - } - - User updatedUser = updateUserReq.left().value(); - - Long lastLoginTime = user.getLastLoginTime(); - if (lastLoginTime != null) { - updatedUser.setLastLoginTime(lastLoginTime); - } else { - updatedUser.setLastLoginTime(new Long(0)); - } - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); - ASDCKpiApi.countUsersAuthorizations(); - return Either.left(updatedUser); - } - - /* - * The method updates user credentials only, the role is neglected The role updated through updateRole method - */ - public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) { - - ResponseFormat responseFormat; - - String userId = updatedUserCred.getUserId(); - - if (userId == null) { - updatedUserCred.setUserId("UNKNOWN"); - log.debug("updateUserCredentials method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } - - Either<User, ActionStatus> eitherCreator = getUser(userId, false); - if (eitherCreator.isRight()) { - ActionStatus status = eitherCreator.right().value(); - if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } else { - return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred)); - } - } else { - if (eitherCreator.left().value() == null) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - User user = eitherCreator.left().value(); - - String firstName = updatedUserCred.getFirstName(); - if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { - user.setFirstName(firstName); - } - - String lastName = updatedUserCred.getLastName(); - if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { - user.setLastName(lastName); - } - - String email = updatedUserCred.getEmail(); - if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { - user.setEmail(email); - } - - if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) { - if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) { - user.setLastLoginTime(updatedUserCred.getLastLoginTime()); - } - } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) { - user.setLastLoginTime(updatedUserCred.getLastLoginTime()); - } - - Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user); - - if (updateUserReq.isRight()) { - responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); - handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); - } - - User updatedUser = updateUserReq.left().value(); - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.left(updatedUser); - } - - private Either<List<Edge>, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { - - Either<List<Edge>, StorageOperationStatus> result = null; - - try { - UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole()); - Map<String, Object> properties = new HashMap<String, Object>(); - switch (userRole) { - case DESIGNER: - case PRODUCT_STRATEGIST: - case PRODUCT_MANAGER: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - case TESTER: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - case ADMIN: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - default: - return Either.left(new ArrayList<>()); - } - } finally { - // commit will be perform outside!!! - if (result == null || result.isRight()) { - log.debug("getUserPendingTasksList failed to perform fetching"); - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - } - - private String getUserPendingTaskStatusByRole(UserRoleEnum role) { - - switch (role) { - case DESIGNER: - case PRODUCT_STRATEGIST: - case PRODUCT_MANAGER: - return "checked-out"; - - case TESTER: - return "in-certification"; - case ADMIN: - return "in-certification/checked-out"; - default: - return ""; - } - } + private static final Logger log = LoggerFactory.getLogger(UserBusinessLogic.class); + private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance(); + + @Resource + private IUserAdminOperation userAdminOperation; + @Resource + private ComponentsUtils componentsUtils; + @Autowired + private TitanGenericDao titanDao; + + @Override + public Either<User, ActionStatus> getUser(String userId, boolean inTransaction) { + return userAdminOperation.getUserData(userId, inTransaction); + } + + @Override + public Either<User, ResponseFormat> createUser(User modifier, User newUser) { + + ResponseFormat responseFormat; + String modifierUserId = modifier.getUserId(); + + if (modifierUserId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("createUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("createUser method - user is not admin = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + // verify user not exist + User userFromDb = new User(); + Either<User, ActionStatus> eitherUserInDB = getUser(newUser.getUserId(), false); + if (eitherUserInDB.isRight()) { + ActionStatus status = eitherUserInDB.right().value(); + if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) { + responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } else {// User exist in DB + userFromDb = eitherUserInDB.left().value(); + if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) { + responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId()); + log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } + + newUser.setStatus(UserStatusEnum.ACTIVE); + + // validate Email + if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) { + log.debug("createUser method - user has invalid email = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + // validate Role + if (newUser.getRole() == null || newUser.getRole().length() == 0) { + newUser.setRole(Role.DESIGNER.name()); + } else { + if (!userAdminValidator.validateRole(newUser.getRole())) { + log.debug("createUser method - user has invalid role = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } + + // handle last login if user is import + if (newUser.getLastLoginTime() == null) { + newUser.setLastLoginTime(0L); + } + + Either<User, StorageOperationStatus> addOrUpdateUserReq; + + if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user + // exist + // with + // inactive + // state + // - + // update + // user + // data + newUser.setLastLoginTime(0L); + addOrUpdateUserReq = userAdminOperation.updateUserData(newUser); + + } else { // user not exist - create new user + + if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) { + log.debug("createUser method - user has invalid userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + addOrUpdateUserReq = userAdminOperation.saveUserData(newUser); + } + + if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) { + log.debug("createUser method - failed to create user"); + Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value()))); + } + log.debug("createUser method - user created"); + User createdUser = addOrUpdateUserReq.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER); + return Either.left(createdUser); + } + + @Override + public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole) { + + ResponseFormat responseFormat; + String modifierUserId = modifier.getUserId(); + + if (modifierUserId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("updateUserRole method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + if (modifier.getUserId().equals(userIdToUpdate)) { + log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false); + if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) { + log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + if (!userAdminValidator.validateRole(userRole)) { + log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + User newUser = new User(); + newUser.setRole(userRole); + newUser.setUserId(userIdToUpdate); + User userToUpdate = userToUpdateReq.left().value(); + // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in + // comment until admin will be able to do do check-in/check-out from the + // UI + + Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); + if (userPendingTasksReq.isRight()) { + log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); + } + + List<Edge> userPendingTasks = userPendingTasksReq.left().value(); + if (!userPendingTasks.isEmpty()) { + log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); + String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); + handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + // } + Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(newUser); + + if (updateUserReq.isRight() || updateUserReq.left().value() == null) { + log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value()))); + } + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + User updatedUser = updateUserReq.left().value(); + handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.left(updatedUser); + } + + @Override + public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context) { + Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null); + + if (response.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value()); + return Either.right(responseFormat); + } + return Either.left(response.left().value()); + } + + @Override + public Either<List<User>, ResponseFormat> getUsersList(String modifierAttId, List<String> roles, String rolesStr) { + ResponseFormat responseFormat; + User user = new User(); + if (modifierAttId == null) { + user.setUserId("UNKNOWN"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + Either<User, ActionStatus> userResult = getUser(modifierAttId, false); + if (userResult.isRight()) { + user.setUserId(modifierAttId); + if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } else { + responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); + } + BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId); + + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + user = userResult.left().value(); + Either<List<User>, ResponseFormat> getResponse = null; + List<User> resultList = new ArrayList<>(); + if (roles != null && !roles.isEmpty()) { + for (String role : roles) { + if (!userAdminValidator.validateRole(role)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + getResponse = getUsersPerRole(role, user, rolesStr); + resultList.addAll(getResponse.left().value()); + } + } else { + rolesStr = "All"; + getResponse = getUsersPerRole(null, user, rolesStr); + resultList.addAll(getResponse.left().value()); + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.left(resultList); + } + + private Either<List<User>, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) { + ResponseFormat responseFormat; + Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name()); + if (response.isRight()) { + responseFormat = componentsUtils.getResponseFormat(response.right().value()); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + return Either.left(response.left().value()); + } + + private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) { + componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat); + } + + private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) { + componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat); + } + + private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) { + componentsUtils.auditUserAccess(actionName, user, responseFormat); + } + + @Override + public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive) { + + ResponseFormat responseFormat; + String userId = modifier.getUserId(); + + if (userId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("deActivateUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> eitherCreator = getUser(userId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + if (modifier.getUserId().equals(userUniuqeIdToDeactive)) { + log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false); + if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) { + log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive)); + } + + User userToDeactivate = getUserToDeleteResponse.left().value(); + if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) { + log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); + if (userPendingTasksReq.isRight()) { + log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); + } + + List<Edge> userPendingTasks = userPendingTasksReq.left().value(); + if (userPendingTasks.size() > 0) { + log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); + String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); + handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either<User, StorageOperationStatus> deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate); + if (deactivateUserReq.isRight()) { + log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value()))); + } + User deactivateUser = deactivateUserReq.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.left(deactivateUser); + } + + @Override + public Either<User, ResponseFormat> authorize(User authUser) { + + ResponseFormat responseFormat; + + String userId = authUser.getUserId(); + + if (userId == null) { + authUser.setUserId("UNKNOWN"); + log.debug("deActivateUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> eitherCreator = getUser(userId, false); + if (eitherCreator.isRight()) { + if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } else { + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser)); + } + } else { + if (eitherCreator.left().value() == null) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + User user = eitherCreator.left().value(); + + String firstName = authUser.getFirstName(); + if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { + user.setFirstName(firstName); + } + + String lastName = authUser.getLastName(); + if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { + user.setLastName(lastName); + } + + String email = authUser.getEmail(); + if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { + user.setEmail(email); + } + + // last login time stamp handle + user.setLastLoginTime(); + + Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user); + + if (updateUserReq.isRight()) { + responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); + handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); + } + + User updatedUser = updateUserReq.left().value(); + + Long lastLoginTime = user.getLastLoginTime(); + if (lastLoginTime != null) { + updatedUser.setLastLoginTime(lastLoginTime); + } else { + updatedUser.setLastLoginTime(new Long(0)); + } + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); + ASDCKpiApi.countUsersAuthorizations(); + return Either.left(updatedUser); + } + + /* + * The method updates user credentials only, the role is neglected The role updated through updateRole method + */ + public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) { + + ResponseFormat responseFormat; + + String userId = updatedUserCred.getUserId(); + + if (userId == null) { + updatedUserCred.setUserId("UNKNOWN"); + log.debug("updateUserCredentials method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } + + Either<User, ActionStatus> eitherCreator = getUser(userId, false); + if (eitherCreator.isRight()) { + ActionStatus status = eitherCreator.right().value(); + if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } else { + return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred)); + } + } else { + if (eitherCreator.left().value() == null) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + User user = eitherCreator.left().value(); + + String firstName = updatedUserCred.getFirstName(); + if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { + user.setFirstName(firstName); + } + + String lastName = updatedUserCred.getLastName(); + if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { + user.setLastName(lastName); + } + + String email = updatedUserCred.getEmail(); + if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { + user.setEmail(email); + } + + if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) { + if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) { + user.setLastLoginTime(updatedUserCred.getLastLoginTime()); + } + } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) { + user.setLastLoginTime(updatedUserCred.getLastLoginTime()); + } + + Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user); + + if (updateUserReq.isRight()) { + responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); + handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); + } + + User updatedUser = updateUserReq.left().value(); + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.left(updatedUser); + } + + private Either<List<Edge>, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { + + Either<List<Edge>, StorageOperationStatus> result = null; + + try { + UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole()); + Map<String, Object> properties = new HashMap<String, Object>(); + switch (userRole) { + case DESIGNER: + case PRODUCT_STRATEGIST: + case PRODUCT_MANAGER: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + case TESTER: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + case ADMIN: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + default: + return Either.left(new ArrayList<>()); + } + } finally { + // commit will be perform outside!!! + if (result == null || result.isRight()) { + log.debug("getUserPendingTasksList failed to perform fetching"); + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + } + + private String getUserPendingTaskStatusByRole(UserRoleEnum role) { + + switch (role) { + case DESIGNER: + case PRODUCT_STRATEGIST: + case PRODUCT_MANAGER: + return "checked-out"; + + case TESTER: + return "in-certification"; + case ADMIN: + return "in-certification/checked-out"; + default: + return ""; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java new file mode 100644 index 0000000000..451989ba36 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java @@ -0,0 +1,7 @@ +package org.openecomp.sdc.be.view; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) +public abstract class Mixin { +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java new file mode 100644 index 0000000000..e3d6ca6e10 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.view; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json representation. + */ +@Provider +@Produces(MediaType.APPLICATION_JSON) +public class MixinModelWriter implements MessageBodyWriter<Object> { + + @Override + public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return hasResponseViewAndMixinTargetAnnotations(annotations) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE); + } + + @Override + public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return -1; + } + + @Override + public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + List<MixinSourceTarget> mixinSourceTargets = getMixinSourceTarget(annotations); + mixinSourceTargets.forEach(mixinSourceTarget -> objectMapper.addMixIn(mixinSourceTarget.getTarget(), mixinSourceTarget.getMixinSource())); + objectMapper.writeValue(entityStream, object); + } + + private List<MixinSourceTarget> getMixinSourceTarget(Annotation[] annotations) { + return Stream.of(annotations) + .filter(annotation -> annotation.annotationType().equals(ResponseView.class)) + .map(annotation -> (ResponseView) annotation) + .flatMap(responseView -> Stream.of(responseView.mixin())) + .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target())) + .collect(Collectors.toList()); + } + + private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) { + return Stream.of(annotations) + .filter(annotation -> annotation.annotationType().equals(ResponseView.class)) + .map(annotation -> (ResponseView) annotation) + .flatMap(responseView -> Stream.of(responseView.mixin())) + .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class))); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java new file mode 100644 index 0000000000..c04c4f88cb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.view; + +/** + * A pojo which holds a mapping between a mixin source and its corresponding target class + */ +public class MixinSourceTarget { + + private Class<?> mixinSource; + private Class<?> target; + + MixinSourceTarget(Class<?> mixinSource, Class<?> target) { + this.mixinSource = mixinSource; + this.target = target; + } + + public Class<?> getMixinSource() { + return mixinSource; + } + + public Class<?> getTarget() { + return target; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java new file mode 100644 index 0000000000..cb44250331 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.view; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface MixinTarget { + /** + * + * @return the class which is the target for the mixin. (i.e the class to be serialized into a json response) + */ + Class<?> target(); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java new file mode 100644 index 0000000000..16733ed019 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.be.view; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface ResponseView { + /** + * The mixins that will be used when converting the resource's response into a specific view of that response. + * A number of mixins can be declared, each of which corresponds to a different object. + */ + public Class<? extends Mixin>[] mixin(); +} + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java index e70b33a938..d7a0f4b8d1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; public interface ICommitHandler extends IDBType { - DBActionCodeEnum doCommit(); + DBActionCodeEnum doCommit(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java index a36e5fe1b5..20763d04f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.transaction.api; public interface IDBAction { - <T> T doAction(); + <T> T doAction(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java index 4c19e41609..3aa2e9a9d7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public interface IDBType { - DBTypeEnum getDBType(); + DBTypeEnum getDBType(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java index 5a10e9029c..ea041359fd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java @@ -20,21 +20,20 @@ package org.openecomp.sdc.common.transaction.api; +import fj.data.Either; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; -import fj.data.Either; - public interface ITransactionSdnc { - TransactionCodeEnum finishTransaction(); + TransactionCodeEnum finishTransaction(); - Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData); + Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData); - <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction); + <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction); - <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction); + <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java index 97a8083e88..a44073971e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java @@ -20,102 +20,105 @@ package org.openecomp.sdc.common.transaction.api; -import java.util.Stack; - import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Stack; + public abstract class RollbackHandler implements IDBType { - private static Logger log = LoggerFactory.getLogger(RollbackHandler.class.getName()); - private Stack<IDBAction> dbActionRollbacks; - - private Integer transactionId; - private String userId, actionType; - - protected RollbackHandler(Integer transactionId, String userId, String actionType) { - if (isRollbackForPersistenceData()) { - dbActionRollbacks = new Stack<>(); - } - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; - } - - public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) { - MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS; - if (isRollbackForPersistenceData()) { - dbActionRollbacks.push(rollbackAction); - } else { - result = MethodActivationStatusEnum.NOT_ALLOWED; - } - return result; - } - - public DBActionCodeEnum doRollback() { - DBActionCodeEnum result; - - try { - if (isRollbackForPersistenceData()) { - result = doPersistenceDataRollback(); - } else { - log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - result = doNonPersistenceDataRollback(); - } - if (result != DBActionCodeEnum.SUCCESS) { - log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); - log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); - } - - } catch (Exception e) { - result = DBActionCodeEnum.FAIL_GENERAL; - log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); - log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e); - log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); - } - - return result; - } - - private <T> DBActionCodeEnum doPersistenceDataRollback() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - while (!dbActionRollbacks.empty()) { - log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - IDBAction rollbackAction = dbActionRollbacks.pop(); - T rollbackResult = rollbackAction.doAction(); - if (!isRollbackResultValid(rollbackResult)) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - } - return result; - } - - /** - * Override for specific logic - * - * @param <T> - */ - public <T> boolean isRollbackResultValid(T rollbackResult) { - return true; - } - - /** - * Override for specific logic - */ - public DBActionCodeEnum doNonPersistenceDataRollback() { - return DBActionCodeEnum.SUCCESS; - } - - protected abstract boolean isRollbackForPersistenceData(); - - /** - * Only Used for Unit Tests ! - */ - public static void setLog(Logger log) { - RollbackHandler.log = log; - } + + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(RollbackHandler.class); + private Stack<IDBAction> dbActionRollbacks; + + private Integer transactionId; + private String userId, actionType; + + protected RollbackHandler(Integer transactionId, String userId, String actionType) { + if (isRollbackForPersistenceData()) { + dbActionRollbacks = new Stack<>(); + } + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; + } + + public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) { + MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS; + if (isRollbackForPersistenceData()) { + dbActionRollbacks.push(rollbackAction); + } else { + result = MethodActivationStatusEnum.NOT_ALLOWED; + } + return result; + } + + public DBActionCodeEnum doRollback() { + DBActionCodeEnum result; + + try { + if (isRollbackForPersistenceData()) { + result = doPersistenceDataRollback(); + } else { + log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + result = doNonPersistenceDataRollback(); + } + if (result != DBActionCodeEnum.SUCCESS) { + log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); + log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); + } + + } catch (Exception e) { + result = DBActionCodeEnum.FAIL_GENERAL; + log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); + log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e); + log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); + } + + return result; + } + + private <T> DBActionCodeEnum doPersistenceDataRollback() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + while (!dbActionRollbacks.empty()) { + log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + IDBAction rollbackAction = dbActionRollbacks.pop(); + T rollbackResult = rollbackAction.doAction(); + if (!isRollbackResultValid(rollbackResult)) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + } + return result; + } + + /** + * Override for specific logic + * + * @param <T> + */ + public <T> boolean isRollbackResultValid(T rollbackResult) { + return true; + } + + /** + * Override for specific logic + */ + public DBActionCodeEnum doNonPersistenceDataRollback() { + return DBActionCodeEnum.SUCCESS; + } + + protected abstract boolean isRollbackForPersistenceData(); + + /** + * Only Used for Unit Tests ! + */ + // TODO test using slf4j-test and remove this + public static void setLog(Logger log) { + RollbackHandler.log = log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java index e90b9618d4..fc7c90509f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java @@ -25,61 +25,61 @@ import org.slf4j.MarkerFactory; public final class TransactionUtils { - private TransactionUtils() { - - } - - public enum DBTypeEnum { - ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT - } - - public enum TransactionCodeEnum { - ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED - } - - public enum TransactionStatusEnum { - OPEN, CLOSED, FAILED_ROLLBACK - } - - public enum DBActionCodeEnum { - SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION - } - - public enum ESActionTypeEnum { - ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT - } - - public enum ActionTypeEnum { - ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE - } - - public static final int MAX_SIZE_TRANSACTION_LIST = 1000; - - public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10; - - public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER"; - - public static final String DUMMY_USER = "udummy"; - - public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR); - - public static class LogMessages { - public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}"; - public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}"; - public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}"; - public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; - public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}"; - public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}"; - public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}"; - public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}"; - public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}"; - public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}"; - public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}"; - public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}"; - public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}"; - } + private TransactionUtils() { + + } + + public enum DBTypeEnum { + ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT + } + + public enum TransactionCodeEnum { + ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED + } + + public enum TransactionStatusEnum { + OPEN, CLOSED, FAILED_ROLLBACK + } + + public enum DBActionCodeEnum { + SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION + } + + public enum ESActionTypeEnum { + ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT + } + + public enum ActionTypeEnum { + ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE + } + + public static final int MAX_SIZE_TRANSACTION_LIST = 1000; + + public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10; + + public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER"; + + public static final String DUMMY_USER = "udummy"; + + public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR); + + public static class LogMessages { + public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}"; + public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}"; + public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}"; + public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; + public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}"; + public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}"; + public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}"; + public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}"; + public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}"; + public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}"; + public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}"; + public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}"; + public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java index 33a8d1163b..0d628cf264 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java @@ -23,36 +23,42 @@ package org.openecomp.sdc.common.transaction.impl; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; +import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.common.transaction.api.IDBAction; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ESAction implements IDBAction { - private ESCatalogDAO esCatalogDao; - private ESArtifactData artifactData; - private ESActionTypeEnum esActionType; - - public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { - this.esCatalogDao = esCatalogDao; - this.artifactData = artifactData; - this.esActionType = esActiontype; - } - - @Override - public DBActionCodeEnum doAction() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - try { - if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) { - esCatalogDao.writeArtifact(artifactData); - } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) { - esCatalogDao.deleteArtifact(artifactData.getId()); - } - - } catch (ResourceDAOException daoException) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + private ESCatalogDAO esCatalogDao; + private ESArtifactData artifactData; + private ESActionTypeEnum esActionType; + + public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { + this.esCatalogDao = esCatalogDao; + this.artifactData = artifactData; + this.esActionType = esActiontype; + } + + @Override + public DBActionCodeEnum doAction() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + try { + if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) { + esCatalogDao.writeArtifact(artifactData); + } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) { + esCatalogDao.deleteArtifact(artifactData.getId()); + } + + } catch (ResourceDAOException daoException) { + result = DBActionCodeEnum.FAIL_GENERAL; + log.error("#doAction - {}, es action failed with error : ", result, daoException); + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java index b9fb0d31b7..e17819fcb0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java @@ -20,73 +20,79 @@ package org.openecomp.sdc.common.transaction.impl; +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.exception.ResourceDAOException; +import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.common.transaction.api.RollbackHandler; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; - -import fj.data.Either; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ESRollbackHandler extends RollbackHandler { - public ESRollbackHandler(Integer transactionId, String userId, String actionType) { - super(transactionId, userId, actionType); - } - - public DBTypeEnum getDBType() { - return DBTypeEnum.ELASTIC_SEARCH; - } - - protected boolean isRollbackForPersistenceData() { - return true; - } - - public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) { - return rollbackResult == DBActionCodeEnum.SUCCESS; - } - - public Either<ESAction, MethodActivationStatusEnum> buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { - Either<ESAction, MethodActivationStatusEnum> result; - - try { - ESAction esRollbackAction = null; - Either<ESArtifactData, ResourceUploadStatus> either = esCatalogDao.getArtifact(artifactData.getId()); - - switch (esActiontype) { - case ADD_ARTIFACT: - - if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) { - esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT); - } - break; - case REMOVE_ARTIFACT: - if (either.isLeft()) { - esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT); - } - break; - case UPDATE_ARTIFACT: - - if (either.isLeft()) { - ESArtifactData originalArtifactData = either.left().value(); - esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT); - } - break; - - } - if (esRollbackAction != null) { - result = Either.left(esRollbackAction); - } else { - result = Either.right(MethodActivationStatusEnum.FAILED); - } - } catch (Exception e) { - result = Either.right(MethodActivationStatusEnum.FAILED); - } - - return result; - } + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + public ESRollbackHandler(Integer transactionId, String userId, String actionType) { + super(transactionId, userId, actionType); + } + + public DBTypeEnum getDBType() { + return DBTypeEnum.ELASTIC_SEARCH; + } + + protected boolean isRollbackForPersistenceData() { + return true; + } + + public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) { + return rollbackResult == DBActionCodeEnum.SUCCESS; + } + + public Either<ESAction, MethodActivationStatusEnum> buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { + Either<ESAction, MethodActivationStatusEnum> result; + + try { + ESAction esRollbackAction = null; + Either<ESArtifactData, ResourceUploadStatus> either = esCatalogDao.getArtifact(artifactData.getId()); + + switch (esActiontype) { + case ADD_ARTIFACT: + + if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) { + esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT); + } + break; + case REMOVE_ARTIFACT: + if (either.isLeft()) { + esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT); + } + break; + case UPDATE_ARTIFACT: + + if (either.isLeft()) { + ESArtifactData originalArtifactData = either.left().value(); + esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT); + } + break; + + } + if (esRollbackAction != null) { + result = Either.left(esRollbackAction); + } else { + result = Either.right(MethodActivationStatusEnum.FAILED); + } + } catch (Exception e) { + result = Either.right(MethodActivationStatusEnum.FAILED); + log.error("#buildEsRollbackAction - {}, es rollback failed with error: ", result, e); + } + + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java index 0d2ec387cf..c86241ebf1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java @@ -28,25 +28,25 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public class TitanCommitHandler implements ICommitHandler { - private TitanGenericDao titanGenericDao; - - public TitanCommitHandler(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public DBActionCodeEnum doCommit() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.commit(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } - - @Override - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } + private TitanGenericDao titanGenericDao; + + public TitanCommitHandler(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + @Override + public DBActionCodeEnum doCommit() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + TitanOperationStatus titanStatus = titanGenericDao.commit(); + if (titanStatus != TitanOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } + + @Override + public DBTypeEnum getDBType() { + return DBTypeEnum.TITAN; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java index c0c686723c..89d2b9da8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java @@ -28,28 +28,28 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public class TitanRollbackHandler extends RollbackHandler { - private TitanGenericDao titanGenericDao; - - public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) { - super(transactionId, userId, actionType); - this.titanGenericDao = titanGenericDao; - } - - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } - - protected boolean isRollbackForPersistenceData() { - return false; - } - - public DBActionCodeEnum doNonPersistenceDataRollback() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.rollback(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } + private TitanGenericDao titanGenericDao; + + public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) { + super(transactionId, userId, actionType); + this.titanGenericDao = titanGenericDao; + } + + public DBTypeEnum getDBType() { + return DBTypeEnum.TITAN; + } + + protected boolean isRollbackForPersistenceData() { + return false; + } + + public DBActionCodeEnum doNonPersistenceDataRollback() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + TitanOperationStatus titanStatus = titanGenericDao.rollback(); + if (titanStatus != TitanOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java index e802e58f27..f366ae214f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.List; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.transaction.api.ICommitHandler; @@ -31,57 +29,60 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public class CommitManager { - private List<ICommitHandler> commitHandlers; - private Integer transactionId; - private String userId, actionType; - private static Logger log = LoggerFactory.getLogger(CommitManager.class.getName()); - CommitManager(Integer transactionId, String userId, String actionType, List<ICommitHandler> commitHandlers) { - this.commitHandlers = commitHandlers; - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(CommitManager.class); + private List<ICommitHandler> commitHandlers; + private Integer transactionId; + private String userId, actionType; + + CommitManager(Integer transactionId, String userId, String actionType, List<ICommitHandler> commitHandlers) { + this.commitHandlers = commitHandlers; + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; - } + } - public DBActionCodeEnum transactionCommit() { - log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType); - DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS; - ICommitHandler lastHandler = null; - try { - for (ICommitHandler handler : commitHandlers) { - lastHandler = handler; - log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType); - DBActionCodeEnum commitCode = handler.doCommit(); - if (commitCode == DBActionCodeEnum.FAIL_GENERAL) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit on DB " + handler.getDBType().name()); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name()); - log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); - commitResult = DBActionCodeEnum.FAIL_GENERAL; - break; - } - log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit - on DB " + getDBName(lastHandler)); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler)); - log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e); - log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler)); - commitResult = DBActionCodeEnum.FAIL_GENERAL; - } - return commitResult; - } + public DBActionCodeEnum transactionCommit() { + log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType); + DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS; + ICommitHandler lastHandler = null; + try { + for (ICommitHandler handler : commitHandlers) { + lastHandler = handler; + log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType); + DBActionCodeEnum commitCode = handler.doCommit(); + if (commitCode == DBActionCodeEnum.FAIL_GENERAL) { + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name()); + log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); + commitResult = DBActionCodeEnum.FAIL_GENERAL; + break; + } + log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler)); + log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e); + log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler)); + commitResult = DBActionCodeEnum.FAIL_GENERAL; + } + return commitResult; + } - private String getDBName(ICommitHandler lastHandler) { - String dbName = "Unknown"; - if (lastHandler != null) { - dbName = lastHandler.getDBType().name(); - } - return dbName; - } + private String getDBName(ICommitHandler lastHandler) { + String dbName = "Unknown"; + if (lastHandler != null) { + dbName = lastHandler.getDBType().name(); + } + return dbName; + } - static void setLog(Logger log) { - CommitManager.log = log; - } + // TODO test using slf4j-test and remove this + static void setLog(Logger log) { + CommitManager.log = log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java index 7098021d1f..80d548ef42 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java @@ -31,56 +31,56 @@ import fj.data.HashMap; import fj.data.List; public class RollbackManager { - private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap; - private final Integer transactionId; - private final String userId; - private final String actionType; + private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap; + private final Integer transactionId; + private final String userId; + private final String actionType; - RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) { - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; - this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i))); - } + RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) { + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; + this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i))); + } - public DBActionCodeEnum transactionRollback() { - List<DBActionCodeEnum> results = rollbackHandlersMap.values().map(RollbackHandler::doRollback); - boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL); - return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS; - } + public DBActionCodeEnum transactionRollback() { + List<DBActionCodeEnum> results = rollbackHandlersMap.values().map(RollbackHandler::doRollback); + boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL); + return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS; + } - protected Either<RollbackHandler, MethodActivationStatusEnum> addRollbackHandler(RollbackHandler rollbackHandler) { - Either<RollbackHandler, MethodActivationStatusEnum> result; - if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) { - result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED); - } else { - rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler); - result = Either.left(rollbackHandler); - } - return result; + protected Either<RollbackHandler, MethodActivationStatusEnum> addRollbackHandler(RollbackHandler rollbackHandler) { + Either<RollbackHandler, MethodActivationStatusEnum> result; + if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) { + result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED); + } else { + rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler); + result = Either.left(rollbackHandler); + } + return result; - } + } - protected Either<RollbackHandler, MethodActivationStatusEnum> createRollbackHandler(final DBTypeEnum dbType) { + protected Either<RollbackHandler, MethodActivationStatusEnum> createRollbackHandler(final DBTypeEnum dbType) { - RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) { + RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) { - @Override - public DBTypeEnum getDBType() { - return dbType; - } + @Override + public DBTypeEnum getDBType() { + return dbType; + } - @Override - protected boolean isRollbackForPersistenceData() { - return true; - } - }; - return addRollbackHandler(rollbackHandler); - } + @Override + protected boolean isRollbackForPersistenceData() { + return true; + } + }; + return addRollbackHandler(rollbackHandler); + } - protected Either<RollbackHandler, MethodActivationStatusEnum> getRollbackHandler(DBTypeEnum dbType) { - // need to swap here because the uses of Either in SDC appears to be opposite of convention - // by convention left is failure; in SDC right is failure - return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap(); - } + protected Either<RollbackHandler, MethodActivationStatusEnum> getRollbackHandler(DBTypeEnum dbType) { + // need to swap here because the uses of Either in SDC appears to be opposite of convention + // by convention left is failure; in SDC right is failure + return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java index c05431ac7f..f218744b84 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java @@ -20,11 +20,8 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.Queue; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Resource; - +import com.google.common.collect.EvictingQueue; +import com.google.common.collect.Queues; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.common.transaction.api.ITransactionSdnc; @@ -34,70 +31,71 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.common.collect.EvictingQueue; -import com.google.common.collect.Queues; +import javax.annotation.Resource; +import java.util.Queue; +import java.util.concurrent.atomic.AtomicInteger; @Component("transactionManager") public class TransactionManager { - private static Logger log = LoggerFactory.getLogger(TransactionManager.class.getName()); - - private AtomicInteger transactionIDCounter = new AtomicInteger(0); - - private Queue<ITransactionSdnc> transactions; - @Resource - private ESCatalogDAO esCatalogDao; - @Resource - private TitanGenericDao titanGenericDao; - - /** - * userId and actionType parameters are used only for logging purposes. - */ - public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) { - if (transactions == null) { - init(); - } - log.debug("TransactionManager creating new SdncTransaction"); - ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao); - transactions.add(tx); - - return tx; - - } - - private Integer generateTransactionID() { - boolean generatedSuccessfully = false; - int nextId = 0; - - while (!generatedSuccessfully) { - int prevId = transactionIDCounter.get(); - if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) { - resetTransactionId(); - } - nextId = prevId + 1; - generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId); - } - return nextId; - } - - private void resetTransactionId() { - - boolean resetSuccessfully = false; - while (!resetSuccessfully) { - int prevId = transactionIDCounter.get(); - resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0); - } - - } - - private synchronized void init() { - if (transactions == null) { - log.info("TransactionManager Initialized"); - EvictingQueue<ITransactionSdnc> queue = EvictingQueue - .<ITransactionSdnc>create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST); - // make thread-safe - transactions = Queues.synchronizedQueue(queue); - } - } + private static final Logger log = LoggerFactory.getLogger(TransactionManager.class); + + private AtomicInteger transactionIDCounter = new AtomicInteger(0); + + private Queue<ITransactionSdnc> transactions; + @Resource + private ESCatalogDAO esCatalogDao; + @Resource + private TitanGenericDao titanGenericDao; + + /** + * userId and actionType parameters are used only for logging purposes. + */ + public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) { + if (transactions == null) { + init(); + } + log.debug("TransactionManager creating new SdncTransaction"); + ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao); + transactions.add(tx); + + return tx; + + } + + private Integer generateTransactionID() { + boolean generatedSuccessfully = false; + int nextId = 0; + + while (!generatedSuccessfully) { + int prevId = transactionIDCounter.get(); + if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) { + resetTransactionId(); + } + nextId = prevId + 1; + generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId); + } + return nextId; + } + + private void resetTransactionId() { + + boolean resetSuccessfully = false; + while (!resetSuccessfully) { + int prevId = transactionIDCounter.get(); + resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0); + } + + } + + private synchronized void init() { + if (transactions == null) { + log.info("TransactionManager Initialized"); + EvictingQueue<ITransactionSdnc> queue = EvictingQueue + .<ITransactionSdnc>create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST); + // make thread-safe + transactions = Queues.synchronizedQueue(queue); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java index 55eff24fa9..bc7b5bde03 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java @@ -20,26 +20,14 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.transaction.api.ICommitHandler; -import org.openecomp.sdc.common.transaction.api.IDBAction; -import org.openecomp.sdc.common.transaction.api.ITransactionSdnc; -import org.openecomp.sdc.common.transaction.api.RollbackHandler; -import org.openecomp.sdc.common.transaction.api.TransactionUtils; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.ActionTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; +import org.openecomp.sdc.common.transaction.api.*; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.*; import org.openecomp.sdc.common.transaction.impl.ESAction; import org.openecomp.sdc.common.transaction.impl.ESRollbackHandler; import org.openecomp.sdc.common.transaction.impl.TitanCommitHandler; @@ -48,266 +36,264 @@ import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; public class TransactionSdncImpl implements ITransactionSdnc { - private boolean lastActionAlreadyCalled; - private RollbackManager rollbackManager; - private CommitManager commitManager; - private ESCatalogDAO esCatalogDao; - private TitanGenericDao titanGenericDao; - private Integer transactionId; - private TransactionStatusEnum status; - private String userId, actionType; - private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class.getName()); - - TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) { - this.esCatalogDao = esCatalogDao; - this.titanGenericDao = titanGenericDao; - this.transactionId = transactionId; - this.userId = userId; - actionType = actionTypeEnum.name(); - rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers()); - commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers()); - status = TransactionStatusEnum.OPEN; - - } - - private List<ICommitHandler> initCommitHandlers() { - List<ICommitHandler> commitHandlers = new ArrayList<>(); - commitHandlers.add(new TitanCommitHandler(titanGenericDao)); - return commitHandlers; - } - - private List<RollbackHandler> initRollbackHandlers() { - List<RollbackHandler> rolebackHandlers = new ArrayList<>(); - rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao)); - rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType)); - return rolebackHandlers; - } - - private <T> Either<T, TransactionCodeEnum> invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) { - - Either<T, DBActionCodeEnum> actionResult; - log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); - if (isLastAction) { - actionResult = getLastActionResult(dbAction, dbType); - } else { - actionResult = getActionResult(dbAction, dbType); - } - - Either<T, TransactionCodeEnum> result; - boolean isRollbackNedded = actionResult.isRight(); - if (isRollbackNedded) { - TransactionCodeEnum transactionCode = transactionRollback(); - result = Either.right(transactionCode); - } else { - result = Either.left(actionResult.left().value()); - } - return result; - } - - private TransactionCodeEnum transactionRollback() { - - TransactionCodeEnum result; - DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback(); - if (transactionRollback == DBActionCodeEnum.SUCCESS) { - result = TransactionCodeEnum.ROLLBACK_SUCCESS; - log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); - - } else { - result = TransactionCodeEnum.ROLLBACK_FAILED; - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit for transaction " + transactionId); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId); - - log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); - } - return result; - } - - public <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction) { - Either<T, TransactionCodeEnum> result; - if (status == TransactionStatusEnum.OPEN) { - result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN); - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - public <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) { - - Either<T, TransactionCodeEnum> result; - MethodActivationStatusEnum addingHandlerResult; - if (status == TransactionStatusEnum.OPEN) { - log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); - Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType); - - if (eitherRollbackHandler.isLeft()) { - RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); - addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction); - } else { - addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction); - } - - if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) { - result = invokeAction(isLastAction, dbAction, dbType); - } else { - result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); - } - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) { - log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType); - MethodActivationStatusEnum result; - - Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType); - if (eitherRollbackHandler.isRight()) { - result = eitherRollbackHandler.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - addToNewRollbackHandler"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler"); - log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); - } else { - RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); - rollbackHandler.addRollbackAction(dbRollbackAction); - result = MethodActivationStatusEnum.SUCCESS; - } - - return result; - } - - public Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) { - - Either<DBActionCodeEnum, TransactionCodeEnum> result; - if (status == TransactionStatusEnum.OPEN) { - Either<RollbackHandler, MethodActivationStatusEnum> eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH); - if (eitherEsHandler.isRight()) { - result = Either.right(TransactionCodeEnum.INTERNAL_ERROR); - } else { - ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value(); - - Either<ESAction, MethodActivationStatusEnum> eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype); - if (eitherEsRollbackAction.isLeft()) { - esHandler.addRollbackAction(eitherEsRollbackAction.left().value()); - result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH); - } else { - result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); - } - - } - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - private <T> void updateTransactionStatus(Either<T, TransactionCodeEnum> result) { - if (result.isRight()) { - updateTransactionStatus(result.right().value()); - } - - } - - private <T> Either<T, TransactionCodeEnum> handleActionOnClosedTransaction() { - Either<T, TransactionCodeEnum> result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - handleActionOnClosedTransaction"); - log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); - return result; - } - - private <T> Either<T, DBActionCodeEnum> getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { - Either<T, DBActionCodeEnum> result; - if (isLastActionAlreadyCalled()) { - result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getLastActionResult"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult"); - log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); - } else { - setLastActionAlreadyCalled(true); - result = getActionResult(dataBaseAction, dbType); - } - return result; - } - - private <T> Either<T, DBActionCodeEnum> getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { - Either<T, DBActionCodeEnum> result; - try { - T doAction = dataBaseAction.doAction(); - result = Either.left(doAction); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getActionResult"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult"); - log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType); - - result = Either.right(DBActionCodeEnum.FAIL_GENERAL); - } - return result; - } - - public TransactionCodeEnum finishTransaction() { - TransactionCodeEnum result; - if (status == TransactionStatusEnum.OPEN) { - DBActionCodeEnum transactionCommit = commitManager.transactionCommit(); - if (transactionCommit == DBActionCodeEnum.SUCCESS) { - result = TransactionCodeEnum.SUCCESS; - status = TransactionStatusEnum.CLOSED; - } else { - result = transactionRollback(); - } - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - finishTransaction"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction"); - log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); - result = TransactionCodeEnum.TRANSACTION_CLOSED; - } - updateTransactionStatus(result); - return result; - } - - private void updateTransactionStatus(TransactionCodeEnum result) { - switch (result) { - case SUCCESS: - status = TransactionStatusEnum.CLOSED; - break; - case ROLLBACK_SUCCESS: - status = TransactionStatusEnum.CLOSED; - break; - case ROLLBACK_FAILED: - status = TransactionStatusEnum.FAILED_ROLLBACK; - break; - default: - break; - } - - } - - private boolean isLastActionAlreadyCalled() { - return lastActionAlreadyCalled; - } - - private void setLastActionAlreadyCalled(boolean lastAction) { - this.lastActionAlreadyCalled = lastAction; - } - - static void setLog(Logger log) { - TransactionSdncImpl.log = log; - } - - TransactionStatusEnum getStatus() { - return status; - } + + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class); + private boolean lastActionAlreadyCalled; + private RollbackManager rollbackManager; + private CommitManager commitManager; + private ESCatalogDAO esCatalogDao; + private TitanGenericDao titanGenericDao; + private Integer transactionId; + private TransactionStatusEnum status; + private String userId, actionType; + + TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) { + this.esCatalogDao = esCatalogDao; + this.titanGenericDao = titanGenericDao; + this.transactionId = transactionId; + this.userId = userId; + actionType = actionTypeEnum.name(); + rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers()); + commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers()); + status = TransactionStatusEnum.OPEN; + + } + + private List<ICommitHandler> initCommitHandlers() { + List<ICommitHandler> commitHandlers = new ArrayList<>(); + commitHandlers.add(new TitanCommitHandler(titanGenericDao)); + return commitHandlers; + } + + private List<RollbackHandler> initRollbackHandlers() { + List<RollbackHandler> rolebackHandlers = new ArrayList<>(); + rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao)); + rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType)); + return rolebackHandlers; + } + + private <T> Either<T, TransactionCodeEnum> invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) { + + Either<T, DBActionCodeEnum> actionResult; + log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); + if (isLastAction) { + actionResult = getLastActionResult(dbAction, dbType); + } else { + actionResult = getActionResult(dbAction, dbType); + } + + Either<T, TransactionCodeEnum> result; + boolean isRollbackNedded = actionResult.isRight(); + if (isRollbackNedded) { + TransactionCodeEnum transactionCode = transactionRollback(); + result = Either.right(transactionCode); + } else { + result = Either.left(actionResult.left().value()); + } + return result; + } + + private TransactionCodeEnum transactionRollback() { + + TransactionCodeEnum result; + DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback(); + if (transactionRollback == DBActionCodeEnum.SUCCESS) { + result = TransactionCodeEnum.ROLLBACK_SUCCESS; + log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); + + } else { + result = TransactionCodeEnum.ROLLBACK_FAILED; + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId); + + log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); + } + return result; + } + + public <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction) { + Either<T, TransactionCodeEnum> result; + if (status == TransactionStatusEnum.OPEN) { + result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN); + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + public <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) { + + Either<T, TransactionCodeEnum> result; + MethodActivationStatusEnum addingHandlerResult; + if (status == TransactionStatusEnum.OPEN) { + log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); + Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType); + + if (eitherRollbackHandler.isLeft()) { + RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); + addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction); + } else { + addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction); + } + + if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) { + result = invokeAction(isLastAction, dbAction, dbType); + } else { + result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); + } + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) { + log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType); + MethodActivationStatusEnum result; + + Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType); + if (eitherRollbackHandler.isRight()) { + result = eitherRollbackHandler.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler"); + log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); + } else { + RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); + rollbackHandler.addRollbackAction(dbRollbackAction); + result = MethodActivationStatusEnum.SUCCESS; + } + + return result; + } + + public Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) { + + Either<DBActionCodeEnum, TransactionCodeEnum> result; + if (status == TransactionStatusEnum.OPEN) { + Either<RollbackHandler, MethodActivationStatusEnum> eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH); + if (eitherEsHandler.isRight()) { + result = Either.right(TransactionCodeEnum.INTERNAL_ERROR); + } else { + ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value(); + + Either<ESAction, MethodActivationStatusEnum> eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype); + if (eitherEsRollbackAction.isLeft()) { + esHandler.addRollbackAction(eitherEsRollbackAction.left().value()); + result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH); + } else { + result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); + } + + } + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + private <T> void updateTransactionStatus(Either<T, TransactionCodeEnum> result) { + if (result.isRight()) { + updateTransactionStatus(result.right().value()); + } + + } + + private <T> Either<T, TransactionCodeEnum> handleActionOnClosedTransaction() { + Either<T, TransactionCodeEnum> result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED); + log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); + return result; + } + + private <T> Either<T, DBActionCodeEnum> getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { + Either<T, DBActionCodeEnum> result; + if (isLastActionAlreadyCalled()) { + result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION); + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult"); + log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); + } else { + setLastActionAlreadyCalled(true); + result = getActionResult(dataBaseAction, dbType); + } + return result; + } + + private <T> Either<T, DBActionCodeEnum> getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { + Either<T, DBActionCodeEnum> result; + try { + T doAction = dataBaseAction.doAction(); + result = Either.left(doAction); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult"); + log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType); + + result = Either.right(DBActionCodeEnum.FAIL_GENERAL); + } + return result; + } + + public TransactionCodeEnum finishTransaction() { + TransactionCodeEnum result; + if (status == TransactionStatusEnum.OPEN) { + DBActionCodeEnum transactionCommit = commitManager.transactionCommit(); + if (transactionCommit == DBActionCodeEnum.SUCCESS) { + result = TransactionCodeEnum.SUCCESS; + status = TransactionStatusEnum.CLOSED; + } else { + result = transactionRollback(); + } + } else { + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction"); + log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); + result = TransactionCodeEnum.TRANSACTION_CLOSED; + } + updateTransactionStatus(result); + return result; + } + + private void updateTransactionStatus(TransactionCodeEnum result) { + switch (result) { + case SUCCESS: + status = TransactionStatusEnum.CLOSED; + break; + case ROLLBACK_SUCCESS: + status = TransactionStatusEnum.CLOSED; + break; + case ROLLBACK_FAILED: + status = TransactionStatusEnum.FAILED_ROLLBACK; + break; + default: + break; + } + + } + + private boolean isLastActionAlreadyCalled() { + return lastActionAlreadyCalled; + } + + private void setLastActionAlreadyCalled(boolean lastAction) { + this.lastActionAlreadyCalled = lastAction; + } + + // TODO test using slf4j-test and remove this + static void setLog(Logger log) { + TransactionSdncImpl.log = log; + } + + TransactionStatusEnum getStatus() { + return status; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java new file mode 100644 index 0000000000..56527b6e9b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.config; + +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; +import org.openecomp.sdc.common.transaction.mngr.TransactionManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan({"org.openecomp.sdc.be.user", + "org.openecomp.sdc.be.impl", + "org.openecomp.sdc.be.auditing.impl", + "org.openecomp.sdc.be.distribution", + "org.openecomp.sdc.be.switchover.detector", + "org.openecomp.sdc.be.tosca", + "org.openecomp.sdc.be.components.validation", + "org.openecomp.sdc.be.components.impl", + "org.openecomp.sdc.be.components.path", + "org.openecomp.sdc.be.components.merge", + "org.openecomp.sdc.be.components.csar", + "org.openecomp.sdc.be.components.property" +}) +public class CatalogBESpringConfig { + @Bean(name = "lifecycleBusinessLogic") + public LifecycleBusinessLogic lifecycleBusinessLogic() { + return new LifecycleBusinessLogic(); + } + + @Bean(name = "transactionManager") + public TransactionManager transactionManager() { + return new TransactionManager(); + } + + @Bean(name = "asset-metadata-utils") + public AssetMetadataConverter assetMetadataConverter() { + return new AssetMetadataConverter(); + } + +} |