import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
-import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Component;
throw new ByResponseFormatComponentException(errorResponse, params);
}
- private Map<String, byte[]> getCsar(User user, Map<String, byte[]> payload, String csarUUID) {
- if (payload != null) {
- return payload;
- }
- Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUUID, user);
- if (csar.isRight()) {
- StorageOperationStatus value = csar.right().value();
- log.debug("#getCsar - failed to fetch csar with ID {}, error: {}", csarUUID, value);
- throw new StorageException(value);
- }
- return csar.left().value();
- }
-
private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Service service, User user,
Map<String, byte[]> payload, String csarUUID) {
Map<String, byte[]> csar = getCsar(service, user, payload, csarUUID);
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.YamlToObjectConverter;
-import org.openecomp.sdc.exception.YamlConversionException;
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;
private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
- /**
- * The main method for testing only
- * @param args
- */
- public static void main(String[] args) throws YamlConversionException {
-
- List<String> servers = new ArrayList<>();
- String server = "uebsb91kcdc.it.att.com:3904";
- servers.add(server);
- servers.add(server);
- servers.add(server);
-
- 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, null);
- distributionEngineInitTask.startTask();
-
- }
-
@Override
public boolean isActive() {
package org.openecomp.sdc.be.components.impl;
-import com.google.common.annotations.VisibleForTesting;
import org.openecomp.sdc.be.model.Service;
/**
private String workloadContext;
private String tenant;
- @VisibleForTesting
- ActivationRequestInformation() {}
-
public ActivationRequestInformation(Service serviceToActivate, String workloadContext, String tenant) {
this.serviceToActivate = serviceToActivate;
this.workloadContext = workloadContext;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.converters.StringConvertor;
import org.openecomp.sdc.be.model.tosca.validators.StringValidator;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import org.springframework.web.context.WebApplicationContext;
-import javax.servlet.ServletContext;
import java.util.List;
@Component("additionalInformationBusinessLogic")
this.additionalInformationOperation = additionalInformationOperation;
}
- 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 nodeType
import com.google.gson.GsonBuilder;
import fj.data.Either;
import io.vavr.control.Option;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.function.Supplier;
import java.util.stream.Collectors;
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 org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
import org.yaml.snakeyaml.Yaml;
@org.springframework.stereotype.Component("artifactBusinessLogic")
}
}
- private boolean isValidXml(byte[] xmlToParse) {
- boolean isXmlValid = true;
- try {
- SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
- saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
- saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
- XMLReader reader = saxParser.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 void validateSingleDeploymentArtifactName(final String artifactName, final Component parentComponent) {
boolean artifactNameFound = false;
final Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
-import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
}
- protected void rollbackWithException(StorageException e) {
- janusGraphDao.rollback();
- throw e;
- }
-
- protected void rollbackWithException(ComponentException e) {
- janusGraphDao.rollback();
- throw e;
- }
-
protected void unlockRollbackWithException(Component component, RuntimeException e) {
janusGraphDao.rollback();
graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
throw new StorageException(storageOperationStatus);
}
- protected PolicyDefinition storageExceptionPolicyDefinition(StorageOperationStatus storageOperationStatus) {
- throw new StorageException(storageOperationStatus);
- }
-
protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) {
throw new ByResponseFormatComponentException(responseFormat);
}
- protected Component componentException(ResponseFormat responseFormat) {
- throw new ByResponseFormatComponentException(responseFormat);
- }
-
protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) {
throw new StorageException(storageOperationStatus);
}
package org.openecomp.sdc.be.components.impl;
import fj.data.Either;
-import io.vavr.Function3;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
- private static final String TAG_FIELD_LABEL = "tag";
-
public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
}
}
- 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) {
try{
validateUserExists(userId);
case RESOURCE_INSTANCE:
return resourceBusinessLogic;
default:
- BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
+ BeEcompErrorManager.getInstance().logBeSystemError("getInstance");
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, componentTypeEnum.getValue());
}
}
return response;
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor() {
- return handleFollowedCertifiedServices(null);
- }
-
private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist() {
// Should be empty list according to Ella, 13/03/16
Map<String, Set<? extends Component>> result = new HashMap<>();
return response;
}
- 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> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
try {
package org.openecomp.sdc.be.components.impl;
-import fj.data.Either;
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
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.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class PolicyTypeBusinessLogic {
- private static final Logger log = Logger.getLogger(PolicyTypeBusinessLogic.class);
private PolicyTypeOperation policyTypeOperation;
private JanusGraphDao janusGraphDao;
private ComponentsUtils componentsUtils;
return policyTypeOperation.getAllPolicyTypes(excludedTypes);
}
- private Either<List<PolicyTypeDefinition>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus err) {
- log.debug("error when trying to fetch policy types: {}", err);
- return componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(err);
- }
-
private PolicyTypeDefinition failOnPolicyType(StorageOperationStatus status, String policyType) {
janusGraphDao.rollback();
if (status == StorageOperationStatus.INVALID_ID) {
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.impl.exceptions.BusinessLogicException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstanceInterface;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
import org.openecomp.sdc.be.resources.data.EntryData;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.context.WebApplicationContext;
-import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
-import java.util.function.Supplier;
@org.springframework.stereotype.Component("propertyBusinessLogic")
interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
}
- 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 Map<String, DataTypeDefinition> getAllDataTypes() {
return getAllDataTypes(applicationDataTypeCache);
}
return propertyCandidate.isPresent();
}
- 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;
- }
- return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
- }
- String innerType;
-
- Either<String, JanusGraphOperationStatus> 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 (!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 (!isEmptyValue(value)) {
- String convertedValue = converter.convert(value, innerType, dataTypes);
- propertyDefinition.setDefaultValue(convertedValue);
- }
- return StorageOperationStatus.OK;
- }
-
- private 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) {
- 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;
- }
-
- private void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
-
- propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
-
- }
-
@Override
protected String getValueFromJsonElement(JsonElement jsonElement) {
if (jsonElement == null || jsonElement.isJsonNull()) {
return jsonElement.toString();
}
- private Either<String, JanusGraphOperationStatus> 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(JanusGraphOperationStatus.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(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
- return Either.left(innerType);
- }
-
@Override
protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
if (isEmptyValue(value)) {
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-import javax.servlet.ServletContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
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.NodeTypeInfoToUpdateArtifacts;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
-import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
resourcesInstancesMap.put(componentInstance, origResource);
}
- private ComponentParametersView getComponentWithInstancesFilter() {
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreInputs(false);
- // inputs are read when creating
- // property values on instances
- parametersView.setIgnoreUsers(false);
- return parametersView;
- }
-
private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
Map<String, List<UploadCapInfo>> uploadedCapabilities) {
for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
}
- /**** 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;
}
import fj.data.Either;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
return responsePair;
}
- private ResponseFormat getResponseFormatFromComponentException(RuntimeException e) {
- if (e instanceof ComponentException) {
- return ((ComponentException) e).getResponseFormat() == null ?
- componentsUtils
- .getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams())
- :
- ((ComponentException) e).getResponseFormat();
- }
- return null;
- }
-
private String getLatestCertifiedResourceId(Resource resource) {
Map<String, String> allVersions = resource.getAllVersions();
Double latestCertifiedVersion = 0.0;
}
}
- private Map<String, Object> getDataTypes(final String payloadData) {
- final Map<String, Object> mappedToscaTemplate = decodePayload(payloadData);
- final Either<Map<String, Object>, ResultStatusEnum> findFirstToscaStringElement =
- ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.DATA_TYPES);
- if (findFirstToscaStringElement.isLeft()) {
- return findFirstToscaStringElement.left().value();
- } else {
- return Collections.EMPTY_MAP;
- }
- }
-
private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) {
if (categories != null && !categories.isEmpty()) {
CategoryDefinition categoryDef = categories.get(0);
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
+import lombok.Getter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.ListUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
import org.openecomp.sdc.be.components.utils.PropertiesUtils;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.DistributionTransitionEnum;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.InputDefinition;
@org.springframework.stereotype.Component("serviceBusinessLogic")
public class ServiceBusinessLogic extends ComponentBusinessLogic {
- private static final String CHANGE_SERVICE_DISTRIBUTION = "Change Service Distribution";
private static final String THE_SERVICE_WITH_SYSTEM_NAME_LOCKED = "The service with system name {} locked. ";
private static final String FAILED_TO_LOCK_SERVICE_RESPONSE_IS = "Failed to lock service {}. Response is {}. ";
private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
return artifactInfo;
}
- private DistributionTransitionEnum validateTransitionEnum(String distributionTransition) {
- DistributionTransitionEnum transitionEnum;
-
- 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());
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_DISTRIBUTION_STATUS, distributionTransition));
- }
-
- return transitionEnum;
- }
-
- private String validateComment(LifecycleChangeInfoWithAction comment) {
- if (comment==null || StringUtils.isEmpty(comment.getUserRemarks())) {
- return "";
- }
- String data = comment.getUserRemarks();
- 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.");
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
- }
- if (!ValidationUtils.validateCommentPattern(data)) {
- throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- return data;
- }
-
- 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, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
- ResourceVersionInfo.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);
}
+ @Getter
class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
- ArtifactDefinition artifactDefinition;
- Service service;
- String resourceInstanceName;
- User modifier;
- String instanceId;
- boolean shouldLock;
- boolean inTransaction;
+ private ArtifactDefinition artifactDefinition;
+ private Service service;
+ private String resourceInstanceName;
+ private User modifier;
+ private String instanceId;
+ private boolean shouldLock;
+ private boolean inTransaction;
HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) {
this.artifactDefinition = artifactDefinition;
return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId);
}
- public ArtifactDefinition getArtifactDefinition() {
- return artifactDefinition;
- }
-
}
class VfModuleArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
return Either.left(Boolean.TRUE);
}
- private Either<Boolean, ResponseFormat> validateAllowedOperationCountOnLocalInterfaceType(
- InterfaceDefinition inputInterfaceDefinition, InterfaceDefinition storedInterfaceDefinition,
- Map<String, InterfaceDefinition> globalInterfaceTypes, boolean isUpdate) {
-
- boolean isInterfaceTypeExistInGlobalType =
- globalInterfaceTypes.values().stream().map(InterfaceDefinition::getType)
- .anyMatch(type -> type.equalsIgnoreCase(inputInterfaceDefinition.getType()));
- if (!isInterfaceTypeExistInGlobalType
- && isValidOperationOnLocalInterfaceType(inputInterfaceDefinition, storedInterfaceDefinition,
- isUpdate)) {
- return Either.right(getResponseFormatManager()
- .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_LOCAL_TYPE,
- inputInterfaceDefinition.getType()));
- }
-
- return Either.left(Boolean.TRUE);
- }
-
- private boolean isValidOperationOnLocalInterfaceType(InterfaceDefinition inputInterfaceDefinition,
- InterfaceDefinition storedInterfaceDefinition,
- boolean isUpdate) {
- return inputInterfaceDefinition.getOperations().size() > 1
- || (!isUpdate && storedInterfaceDefinition != null
- && storedInterfaceDefinition.getType()
- .equalsIgnoreCase(inputInterfaceDefinition.getType()));
- }
-
private Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType(
InterfaceDefinition interfaceDefinition, Map<String, InterfaceDefinition> globalInterfaceTypes) {
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.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.servers.Server;
-import io.swagger.v3.oas.annotations.servers.Servers;
import io.swagger.v3.oas.annotations.tags.Tag;
-import io.swagger.v3.oas.annotations.tags.Tags;
import java.io.IOException;
import java.util.List;
import org.openecomp.sdc.be.servlets.*;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.log.elements.LoggerSupportability;
import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
import org.openecomp.sdc.common.log.enums.StatusCode;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
-@Tags({@Tag(name = "SDC External APIs")})
-@Servers({@Server(url = "/sdc")})
+@Tag(name = "SDC External APIs")
+@Server(url = "/sdc")
@Controller
public class AbstractTemplateServlet extends AbstractValidationsServlet {
this.resourceBusinessLogic = resourceBusinessLogic;
}
- 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;
- }
-
/**
* @param requestId
* @param instanceIdHeader
return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
}
- private CopyServiceInfo convertJsonToServiceInfo(String data) {
- ObjectMapper mapper = new ObjectMapper();
- try {
- return mapper.readValue(data, CopyServiceInfo.class);
- } catch (IOException e) {
- log.error("#convertJsonToServiceInfo - json deserialization failed with error: ", e);
- return new CopyServiceInfo();
- }
- }
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
-import fj.data.Either;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.glassfish.jersey.server.ContainerRequest;
-import org.onap.sdc.security.Passwords;
-import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
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.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.ConsumerDefinition;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.log.enums.LogLevel;
import org.openecomp.sdc.common.log.enums.Severity;
private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class);
private static final Logger log = Logger.getLogger(BasicAuthenticationFilter.class);
private static final String COMPONENT_UTILS_FAILED = "Authentication Filter Failed to get component utils.";
- private static final String CONSUMER_BL_FAILED = "Authentication Filter Failed to get consumerBL.";
private static final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
private static final Configuration.BasicAuthConfig basicAuthConf = configurationManager.getConfiguration().getBasicAuth();
}
}
- 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 {
- abortWith(requestContext, CONSUMER_BL_FAILED, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
- }
- } else {
- ConsumerDefinition consumerCredentials = result.left().value();
-
- }
- }
-
private void authSuccessful(ContainerRequestContext requestContext, String userName) {
ComponentsUtils componentUtils = getComponentsUtils();
if (componentUtils == null) {
}
}
- private void authUserNotFoundError(ContainerRequestContext requestContext, String userName) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- abortWith(requestContext, COMPONENT_UTILS_FAILED, 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);
- abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false));
- }
-
private void authInvalidHeaderError(ContainerRequestContext requestContext) {
ComponentsUtils componentUtils = getComponentsUtils();
if (componentUtils == null) {
return webApplicationContext.getBean(ComponentsUtils.class);
}
- private ConsumerBusinessLogic getConsumerBusinessLogic() {
- ServletContext context = sr.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(ConsumerBusinessLogic.class);
- }
-
public enum AuthStatus {
AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS
}
package org.openecomp.sdc.be.filters;
import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper;
import org.openecomp.sdc.common.api.FilterDecisionEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
ThreadLocalsHolder.setApiType(FilterDecisionEnum.NA);
threadLocalUtils.setUserContextFromDB(httpRequest);
filterChain.doFilter(httpRequest, res);
-// } else if (isCookieExist(httpRequest, authCookieConf.getCookieName())) {
-// ThreadLocalsHolder.setApiType(FilterDecisionEnum.INTERNAL);
-// filterChain.doFilter(httpRequest, res);
-// } else {
-// validateAuthHeaderExist(httpRequest);
-// ThreadLocalsHolder.setApiType(FilterDecisionEnum.EXTERNAL);
-// filterChain.doFilter(httpRequest, res);
}
} catch (ComponentException ce) {
componentExceptionMapper.writeToResponse(ce, httpResponse);
httpResponse.setCharacterEncoding("UTF-8");
}
- private boolean isCookieExist(HttpServletRequest httpRequest, String cookieName) {
- Cookie[] cookies = httpRequest.getCookies();
- if (cookies != null) {
- for (Cookie cookie : cookies) {
- if (cookie.getName().equals(cookieName)) {
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean isHeaderExist(HttpServletRequest req, String headerName) {
- return req.getHeader(headerName) != null;
- }
-
- private void validateAuthHeaderExist(HttpServletRequest req) {
- boolean authHeader = isHeaderExist(req, HttpHeaders.AUTHORIZATION);
- if (!authHeader) throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED);
- }
-
private boolean isUrlFromWhiteList(HttpServletRequest httpRequest) {
String pathInfo;
List<String> excludedUrls = authCookieConf.getExcludedUrls();
package org.openecomp.sdc.be.filters;
-import com.google.common.annotations.VisibleForTesting;
-import org.apache.commons.lang.StringUtils;
-import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
import org.onap.sdc.security.IPortalConfiguration;
import org.onap.sdc.security.PortalClient;
-import java.security.InvalidParameterException;
-
public class PortalConfiguration implements IPortalConfiguration {
- private static final String PROPERTY_NOT_SET = "%s property value is not set in portal.properties file";
+
private String portalUser;
private String portalPassword;
private String ecompPortalRestURL;
this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value());
}
- @VisibleForTesting
- String getPortalProperty(String key) {
- String value = PortalApiProperties.getProperty(key);
- if (StringUtils.isEmpty(value)) {
- throw new InvalidParameterException(String.format(PROPERTY_NOT_SET, key));
- }
- return value;
- }
-
@Override
public String getPortalApiPrefix() {
return null;
} else log.debug("user_id value in req header is null, userContext will not be initialized");
}
- protected void setUserContextFromDB(AuthenticationCookie authenticationCookie) {
- String user_id = authenticationCookie.getUserID();
- updateUserContext(user_id);
- }
-
private void updateUserContext(String user_id) {
User user = userBusinessLogic.getUser(user_id, false);
Set<String> roles = new HashSet<>(Arrays.asList(user.getRole()));
import com.google.common.collect.SetMultimap;
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;
}
- protected ResponseFormatManager getResponseFormatManager() {
- return ResponseFormatManager.getInstance();
- }
-
public Set<String> findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService,
String componentInstanceId) {
return findForwardingPathToDeleteOnCIDeletion(containerService, componentInstanceId).values().stream()
package org.openecomp.sdc.be.info;
-import com.google.common.annotations.VisibleForTesting;
import lombok.Getter;
+import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
+@NoArgsConstructor
public class ServiceVersionInfo {
private String version;
private String url;
- @VisibleForTesting
- ServiceVersionInfo() {}
-
public ServiceVersionInfo(String serviceName, String serviceVersion, String context) {
super();
this.version = serviceVersion;
import org.json.simple.parser.ParseException;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
-import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
-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.GenericArtifactBrowserBusinessLogic;
import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
import org.openecomp.sdc.be.components.impl.OutputsBusinessLogic;
import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
-import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;
-import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
-import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
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.datatypes.enums.DeclarationTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-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.ComponentInstInputsMap;
return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
}
- InterfaceOperationBusinessLogic getInterfaceOperationBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> InterfaceOperationBusinessLogic.class);
- }
-
- protected CapabilitiesBusinessLogic getCapabilitiesBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> CapabilitiesBusinessLogic.class);
- }
-
- protected RelationshipTypeBusinessLogic getRelationshipTypeBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> RelationshipTypeBusinessLogic.class);
- }
- protected RequirementBusinessLogic getRequirementBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> RequirementBusinessLogic.class);
- }
- ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
- }
-
protected ServiceBusinessLogic getServiceBL(ServletContext context) {
return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
}
- ProductBusinessLogic getProductBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
- }
-
protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
}
- protected UpgradeBusinessLogic getUpgradeBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> UpgradeBusinessLogic.class);
- }
protected ElementBusinessLogic getElementBL(ServletContext context) {
return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
}
- protected AssetMetadataConverter getAssetUtils(ServletContext context) {
- return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
- }
-
- protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
- }
-
<T> T getClassFromWebAppContext(final ServletContext context, final Supplier<Class<T>> businessLogicClassGen) {
return getWebAppContext(context).getBean(businessLogicClassGen.get());
}
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;
- }
-
<T> T convertJsonToObjectOfClass(String json, Class<T> clazz) {
T object = null;
ObjectMapper mapper = new ObjectMapper()
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.servers.Server;
-import io.swagger.v3.oas.annotations.servers.Servers;
import io.swagger.v3.oas.annotations.tags.Tag;
-import io.swagger.v3.oas.annotations.tags.Tags;
import org.apache.commons.lang3.tuple.Pair;
import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
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.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckWrapper;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Controller;
-import org.springframework.web.context.WebApplicationContext;
import javax.inject.Inject;
import javax.servlet.ServletContext;
@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
@Path("/")
-@Tags({@Tag(name = "SDC Internal APIs")})
-@Servers({@Server(url = "/sdc2/rest")})
+@Tag(name = "SDC Internal APIs")
+@Server(url = "/sdc2/rest")
@Controller
public class BeMonitoringServlet extends BeGenericServlet {
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
+ private final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- private static final Logger log = Logger.getLogger(ConfigServlet.class);
+ private static final Logger log = Logger.getLogger(BeMonitoringServlet.class);
private final HealthCheckBusinessLogic healthCheckBusinessLogic;
@Inject
}
}
-
- //TODO remove after UI alignment and tests after API consolidation ASDC-191
- /*@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();
return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
}
- private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(HealthCheckBusinessLogic.class);
- }
-
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
- //String createDate = format.format(new Date(component.getCreationDate()));
+
Date date = new Date();
String releaseTime = format.format(date);
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);
return componentTypeArtifacts;
}
- public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
- this.componentTypeArtifacts = componentTypeArtifacts;
- }
}
private class CsarDefinition {
+++ /dev/null
-/*-
- * ============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;
-
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.common.api.BasicConfiguration;
-import org.openecomp.sdc.common.api.ConfigurationListener;
-import org.openecomp.sdc.common.api.ConfigurationSource;
-import org.openecomp.sdc.common.api.FileChangeCallback;
-import org.openecomp.sdc.common.impl.ConfigFileChangeListener;
-import org.openecomp.sdc.common.impl.ExternalConfiguration;
-import org.openecomp.sdc.common.impl.FSConfigurationSource;
-
-import java.io.IOException;
-
-public class TestExternalConfiguration<T extends Object> {
-
- public static void main(String[] args) throws IOException {
-
- ExternalConfiguration.setAppName("catalog-server");
- ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config");
- ExternalConfiguration.listenForChanges();
-
- ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() {
-
- @Override
- public void reconfigure(BasicConfiguration obj) {
- // TODO Auto-generated method stub
-
- }
- });
-
- ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir());
- configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener);
-
- try {
- Thread.currentThread().sleep(100 * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- }
-
-}
private static final String TENANT = "tenant";
private static final String WORKLOAD_CONTEXT = "workloadContext";
- @Test
- public void shouldHaveValidGettersAndSetters() {
- assertThat(ActivationRequestInformation.class, hasValidGettersAndSetters());
- }
-
@Test
public void testFullArgConstructor() {
Service serviceToActivate = new Service();
testSubject.fillArtifactPayload(payloadWrapper, artifactDefinition);
}
-
-
- @Test
- public void testIsValidXml() throws Exception {
- ArtifactsBusinessLogic testSubject;
- byte[] xmlToParse = new byte[]{' '};
- boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = Deencapsulation.invoke(testSubject, "isValidXml", new Object[]{xmlToParse});
- }
-
@Test(expected = ByActionStatusComponentException.class)
public void testHeatTimeoutValue() {
final ArtifactsBusinessLogic artifactsBusinessLogic = createTestSubject();
assertThat(result.getId()).isEqualTo(cpOption.getId());
}
- @Test
- public void testGetResponseFormatManager() {
- ForwardingPathUtils testSubject;
- ResponseFormatManager result;
-
- // default test
- testSubject = createTestSubject();
- result = Deencapsulation.invoke(testSubject, "getResponseFormatManager");
- assertThat(result).isInstanceOf(ResponseFormatManager.class);
- }
-
@Test
public void testFindForwardingPathNamesToDeleteOnComponentInstanceDeletion() throws Exception {
ForwardingPathUtils testSubject;
import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
import java.util.Map;
-import java.util.stream.Collectors;
/**
* Specifies the capabilities that the Node Type exposes.
public CapabilityTypeDefinition(CapabilityTypeDataDefinition p) {
super(p);
}
-
- public CapabilityTypeDefinition(CapabilityDefinition cp) {
- this.setUniqueId(cp.getUniqueId());
- this.setDescription ( cp.getDescription());
- this.setType(cp.getType());
- this.setValidSourceTypes( cp.getValidSourceTypes());
- this.setProperties(cp.getProperties().stream().collect(Collectors.toMap(ComponentInstanceProperty::getName, PropertyDefinition::new)));
- }
public CapabilityTypeDefinition(CapabilityTypeData ctd) {
this.setUniqueId(ctd.getUniqueId());
import java.util.List;
import java.util.Map;
+import lombok.Getter;
+import lombok.Setter;
import org.openecomp.sdc.be.ui.model.UiCombination;
+@Getter
+@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Combination {
private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties;
private Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes;
- public Combination() {
- }
// To form the combination object with the data received from UI
public Combination(UiCombination UICombination) {
name = UICombination.getName();
description = UICombination.getDescription();
}
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDesc() {
- return description;
- }
-
- public void setDesc(String description) {
- this.description = description;
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- public List<ComponentInstance> getComponentInstances() {
- return componentInstances;
- }
-
- public void setComponentInstances(List<ComponentInstance> componentInstances) {
- this.componentInstances = componentInstances;
- }
-
- public List<RequirementCapabilityRelDef> getComponentInstancesRelations() {
- return componentInstancesRelations;
- }
-
- public void setComponentInstancesRelations(List<RequirementCapabilityRelDef> componentInstancesRelations) {
- this.componentInstancesRelations = componentInstancesRelations;
- }
-
- public Map<String, List<ComponentInstanceInput>> getComponentInstancesInputs() {
- return componentInstancesInputs;
- }
-
- public void setComponentInstancesInputs(Map<String, List<ComponentInstanceInput>> componentInstancesInputs) {
- this.componentInstancesInputs = componentInstancesInputs;
- }
-
- public Map<String, List<ComponentInstanceProperty>> getComponentInstancesProperties() {
- return componentInstancesProperties;
- }
-
- public void setComponentInstancesProperties(Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
- this.componentInstancesProperties = componentInstancesProperties;
- }
-
- public Map<String, List<ComponentInstanceProperty>> getComponentInstancesAttributes() {
- return componentInstancesAttributes;
- }
-
- public void setComponentInstancesAttributes(Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes) {
- this.componentInstancesAttributes = componentInstancesAttributes;
- }
-}
\ No newline at end of file
+}
}
}
- // @TODO add implementation
-
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) {
- return null;
- }
-
public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv,
ArtifactDefinition artifactHeat, Component component, NodeTypeEnum parentType, boolean failIfExist, String instanceId) {
artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId());
}
protected Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) {
-// healingPipelineDao.setHealingVersion(dataVertex);
Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name());
int edgeCount = 0;
Edge edgeToRemove = null;
return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField);
}
- /**
- * Adds tosca data deep element to tosca element according received labels
- *
- * @param toscaElement
- * @param edgeLabel
- * @param vertexLabel
- * @param toscaData
- * @param pathKeys
- * @param mapKeyField
- * @return
- */
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
- List<T> toscaDataList = new ArrayList<>();
- toscaDataList.add(toscaData);
- return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField);
- }
-
- /**
- * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels
- *
- * @param toscaElement
- * @param edgeLabel
- * @param vertexLabel
- * @param toscaDataMap
- * @param pathKeys
- * @param mapKeyField
- * @return
- */
- public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, List<String> pathKeys,
- JsonPresentationFields mapKeyField) {
-
- if (toscaDataMap != null) {
- return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField);
- }
- return StorageOperationStatus.OK;
- }
-
/**
* Adds list of tosca data deep elements to tosca element according received labels
*
return value == null;
}
- public boolean isNullParam(String value) {
- return value == null;
- }
-
protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
super();
}
- public JanusGraphGenericDao getJanusGraphGenericDao() {
- return janusGraphGenericDao;
- }
-
- public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) {
- this.janusGraphGenericDao = janusGraphGenericDao;
- }
-
- public HeatParametersOperation getHeatParametersOperation() {
- return heatParametersOperation;
- }
-
- public void setHeatParametersOperation(HeatParametersOperation heatParametersOperation) {
- this.heatParametersOperation = heatParametersOperation;
- }
-
public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, boolean inTransaction) {
Either<ArtifactData, StorageOperationStatus> status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist);
}
- public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, JanusGraphVertex parentVertex) {
-
- StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex);
-
- if (status.equals(StorageOperationStatus.OK)) {
- log.debug("Failed to add artifact {} {} to {}", artifactInfo.getArtifactName(), type, parentId);
- }
- return status;
- }
-
- private StorageOperationStatus addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist, JanusGraphVertex parentVertex) {
-
- if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel());
- artifactInfo.setUniqueId(uniqueId);
- }
-
- if (!validateParentType(type)) {
- return StorageOperationStatus.GENERAL_ERROR;
- }
-
- ArtifactData artifactData = new ArtifactData(artifactInfo);
-
- Either<JanusGraphVertex, JanusGraphOperationStatus> existArtifact = janusGraphGenericDao
- .getVertexByProperty(artifactData.getUniqueIdKey(), artifactData.getUniqueId());
- if (existArtifact.isRight()) {
- if (existArtifact.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
- // create new node
- log.debug("Before adding artifact to graph {}", artifactData);
- if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty())
- updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion());
- Either<JanusGraphVertex, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao.createNode(artifactData);
-
- if (createNodeResult.isRight()) {
- JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
- log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus);
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus);
- }
-
- // add heat parameters
- if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
- if (addPropertiesStatus != StorageOperationStatus.OK) {
- log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName());
- return addPropertiesStatus;
- }
- }
-
- } else {
- log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId());
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(existArtifact.right().value());
- }
- } else if (failIfexist) {
- log.debug("Artifact {} already exist", artifactData.getUniqueId());
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ALREADY_EXIST);
- }
-
- // save logical artifact ref name on edge as property
- Map<String, Object> properties = new HashMap<>();
- properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel());
- if (artifactInfo.getArtifactGroupType() != null)
- properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType());
- JanusGraphOperationStatus relation = janusGraphGenericDao
- .createEdge(parentVertex, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties);
- if (!relation.equals(JanusGraphOperationStatus.OK)) {
- log.debug("Failed to create relation in graph for id {} to new artifact", id);
- return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(relation);
- }
-
- return StorageOperationStatus.OK;
- }
-
private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist) {
if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) {
import static org.springframework.util.CollectionUtils.isEmpty;
-import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import fj.data.Either;
import java.util.ArrayList;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
this.capabilityTypeOperation = capabilityTypeOperation;
this.propertyOperation = propertyOperation;
}
-
-
- @VisibleForTesting
- public void setJanusGraphGenericDao(HealingJanusGraphGenericDao janusGraphGenericDao) {
- this.janusGraphGenericDao = janusGraphGenericDao;
- }
+
public Either<CapabilityData, JanusGraphOperationStatus> addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData, CapabilityDefinition capabilityDefinition) {
@javax.annotation.Resource
private OnboardingClient onboardingClient;
- public static void main(String[] args) {
-
- CsarOperation csarOperation = new CsarOperation();
- csarOperation.init();
-
- String csarUuid = "70025CF6081B489CA7B1CBA583D5278D";
- Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null);
- System.out.println(csar.left().value());
-
- }
-
@PostConstruct
public void init() {
import fj.data.Either;
import java.util.Map;
import java.util.Properties;
+import lombok.NoArgsConstructor;
import org.apache.http.HttpStatus;
import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.zip.ZipUtils;
+@NoArgsConstructor
@org.springframework.stereotype.Component("onboarding-client")
public class OnboardingClient {
downloadCsarHeaders.put("Accept", "application/octet-stream");
}
- public OnboardingClient() {
- super();
- }
-
- public static void main(String[] args) {
-
- OnboardingClient csarOperation = new OnboardingClient();
-
- String csarUuid = "70025CF6081B489CA7B1CBA583D5278D";
- Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null);
- System.out.println(csar.left().value());
-
- }
-
public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) {
String url = buildDownloadCsarUrl() + "/" + csarUuid;
private static final String PROPERTY = "Property";
private static final String UPDATE_DATA_TYPE = "UpdateDataType";
- public static void main(String[] args) {
-
- List<Pattern> buildFunctionPatterns = buildFunctionPatterns();
-
- for (Pattern pattern : buildFunctionPatterns) {
-
- String[] strs = { "str_replace", "{ str_replace:", " {str_replace:", " { str_replace:", "{str_replace:" };
- for (String str : strs) {
- Matcher m = pattern.matcher(str);
- System.out.println(pattern.pattern() + " " + str + " " + m.find());
- }
- }
-
- }
-
@Autowired
public PropertyOperation(HealingJanusGraphGenericDao janusGraphGenericDao, DerivedFromOperation derivedFromOperation) {
this.janusGraphGenericDao = janusGraphGenericDao;
private static Logger log = Logger.getLogger(PropertyOperation.class.getName());
- /**
- * The value of functions is in a json format. Build pattern for each function name
- *
- * { str_replace: .... } {str_replace: .... } {str_replace: .... } { str_replace: .... }
- *
- * @return
- */
- private static List<Pattern> buildFunctionPatterns() {
-
- List<Pattern> functionPatterns = new ArrayList<>();
-
- String[] functions = { "get_input", "get_property" };
-
- for (String function : functions) {
- Pattern pattern = Pattern.compile("^[ ]*\\{[ ]*" + function + ":");
- functionPatterns.add(pattern);
- }
-
- return functionPatterns;
- }
-
public PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
log.debug("The object returned after create property is {}", propertyDataResult);
public class ApplicationVersionException extends TechnicalException {
- public ApplicationVersionException(String message, Throwable cause) {
- super(message, cause);
- }
-
public ApplicationVersionException(String message) {
super(message);
}
import org.mockito.Mockito;
import org.openecomp.sdc.be.ui.model.UiCombination;
-import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
-import static org.hamcrest.MatcherAssert.assertThat;
-
public class CombinationTest {
@Test
new Combination(uiComb);
}
- @Test
- public void shouldHaveValidGettersAndSetters() {
- assertThat(Combination.class, hasValidGettersAndSetters());
- }
-}
\ No newline at end of file
+}
}
- /*
- * @Test public void addPropertyToResourceTest() {
- *
- * String propName = "myProp"; PropertyDefinition property = buildPropertyDefinition(); List<PropertyConstraint> constraints = buildConstraints(); property.setConstraints(constraints);
- *
- * PropertyData propertyData = new PropertyData(property, propertyOperation.convertConstraintsToString(constraints));
- *
- * Either<PropertyData, JanusGraphOperationStatus> either = Either.left(propertyData); //when(propertyDao.create((GraphNeighbourTable)anyObject(), eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); GraphRelation graphRelation =
- * new GraphRelation(); Either<GraphRelation, JanusGraphOperationStatus> relationResult = Either.left(graphRelation);
- *
- * when(janusGraphGenericDao.createNode((PropertyData)anyObject(), eq(PropertyData.class))).thenReturn(either); when(janusGraphGenericDao.createRelation((GraphNode)anyObject(), (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY),
- * anyMap())).thenReturn(relationResult);
- *
- * Either<PropertyDefinition, StorageOperationStatus> result = propertyOperation.addPropertyToResource(propName, property, NodeTypeEnum.Resource, "my-resource.1.0");
- *
- * assertTrue(result.isLeft()); System.out.println(result.left().value()); PropertyDefinition propertyDefinition = result.left().value();
- *
- * List<PropertyConstraint> originalConstraints = property.getConstraints(); List<PropertyConstraint> propertyConstraintsResult = propertyDefinition.getConstraints(); assertEquals(propertyConstraintsResult.size(), originalConstraints.size());
- *
- * }
- */
private PropertyDefinition buildPropertyDefinition() {
PropertyDefinition property = new PropertyDefinition();
property.setDefaultValue("10");
return property;
}
- @Test
- public void addPropertiesToGraphTableTest() {
-
- // Map<String, PropertyDefinition> properties = new HashMap<String,
- // PropertyDefinition>();
- // String propName = "myProp";
- // PropertyDefinition property = buildPropertyDefinition();
- //
- // List<PropertyConstraint> constraints = buildConstraints();
- // property.setConstraints(constraints);
- //
- // properties.put(propName, property);
- //
- // GraphNeighbourTable graphNeighbourTable = new GraphNeighbourTable();
- // ResourceData resourceData = new ResourceData();
- // String resourceName = "my-resource";
- // String resourceVersion = "1.0";
- // String resourceId = resourceName + "." + resourceVersion;
- // resourceData.setUniqueId(resourceId);
- // int resourceIndex = graphNeighbourTable.addNode(resourceData);
- //
- // heatParametersOperation.addPropertiesToGraphTable(properties,
- // graphNeighbourTable, resourceIndex, resourceId);
- //
- // assertEquals(2, graphNeighbourTable.getNodes().size());
- // assertEquals(1, graphNeighbourTable.getDirectedEdges().size());
- // List<GraphNode> nodes = graphNeighbourTable.getNodes();
- // boolean nodeFound = false;
- // for (GraphNode neo4jNode : nodes) {
- // if (neo4jNode instanceof PropertyData) {
- // PropertyData propertyData = (PropertyData)neo4jNode;
- // assertEquals("check property unique id", resourceId + "." + propName,
- // propertyData.getUniqueId());
- // assertEquals(property.getDescription(),
- // propertyData.getPropertyDataDefinition().getDescription());
- // nodeFound = true;
- // }
- // }
- // assertEquals("looking for PropertyData object in table", true,
- // nodeFound);
- //
- // NodeRelation nodeRelation =
- // graphNeighbourTable.getDirectedEdges().get(0);
- // assertEquals("check from index to index edge", 0,
- // nodeRelation.getFromIndex());
- // assertEquals("check from index to index edge", 1,
- // nodeRelation.getToIndex());
- // assertEquals("check edge type",
- // GraphEdgePropertiesDictionary.PROPERTY,
- // nodeRelation.getEdge().getEdgeType());
- // assertEquals("check propert name on edge", true,
- // nodeRelation.getEdge().getProperties().values().contains(propName));
- }
-
@Test
public void convertConstraintsTest() {
return new PropertyOperation(new HealingJanusGraphGenericDao(new JanusGraphClient()), null);
}
-
- @Test
- public void testMain() throws Exception {
- String[] args = new String[] { "" };
-
- // default test
- PropertyOperation.main(args);
- }
-
-
@Test
public void testConvertPropertyDataToPropertyDefinition() throws Exception {
PropertyOperation testSubject;
package org.openecomp.sdc.common.api;
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-
-import java.lang.reflect.Type;
import java.util.List;
public class HealthCheckInfo {
this.description = description;
}
- /*public enum HealthCheckComponent {
- FE, BE, JANUSGRAPH, DE, ON_BOARDING, CASSANDRA, DCAE,
- CAS, ZU;//Amdocs components
- }*/
-
public enum HealthCheckStatus {
UP, DOWN, UNKNOWN;
}
+ componentsInfo + "]";
}
- public static void main(String[] args) {
- String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]";
- Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType();
- List<HealthCheckInfo> componentsInfo = new Gson().fromJson(des.toString(), listType);
- System.out.println(componentsInfo.toString());
- }
}
I, W, E, F;
}
- public static void main(String[] args) {
- System.out.println(Arrays.asList(EcompErrorType.values()));
- }
}
private static String NEW_LINE = System.getProperty("line.separator");
- private static void usage() {
- System.out.println("java org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv <target folder>");
- System.exit(1);
- }
-
- public static void main(String[] args) {
-
- String targetFolder = "target";
- if (args.length > 1) {
- targetFolder = args[0];
- }
-
- GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv();
-
- ecompErrorsCsv.generateEcompErrorsCsvFile(targetFolder, true);
- }
-
public static class EcompErrorRow {
String errorName;
result = testSubject.toString();
}
- @Test
- public void testMain() throws Exception {
- String[] args = new String[] { "" };
-
- // default test
- HealthCheckInfo.main(args);
- }
}
assertEquals(ecompErrorConfiguration.getErrors(), errors);
}
- @Test
- public void testMain() throws Exception {
- String[] args = new String[] {""};
-
- // default test
- EcompErrorConfiguration.main(args);
- }
-
-}
\ No newline at end of file
+}
result = testSubject.generateEcompErrorsCsvFile(targetFolder, addTimeToFileName);
}
-
- @Test
- public void testMain() throws Exception {
- String[] args = new String[] { "" };
-
- // default test
- GenerateEcompErrorsCsv.main(args);
- }
}
+++ /dev/null
-/*-
- * ============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.workers;
-
-/**
- * Created by michael on 6/24/2016.
- */
-public abstract class Job<E> {
- public abstract E doWork();
-
-}
+++ /dev/null
-/*-
- * ============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.workers;
-
-/**
- * Created by michael on 6/24/2016.
- */
-public class Main {
-
- public static void main(String[] args) {
-
- Manager manger = new Manager();
- manger.init(2);
- manger.addJob(new Job() {
- @Override
- public String doWork() {
- return "go";
- }
- });
- manger.addJob(new Job() {
- @Override
- public String doWork() {
- return "go go";
- }
- });
- // try {
- System.out.println(manger.start());
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- }
-}
+++ /dev/null
-/*-
- * ============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.workers;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Created by michael on 6/24/2016.
- */
-public class Manager<T extends Job, E> {
- private static final int TERMINATION_TIMEAUT = 30;
- private static Logger log = Logger.getLogger(Manager.class.getName());
- private ExecutorService executor;
- private LinkedBlockingQueue<T> inputQueue;
- private LinkedBlockingQueue<E> outputQueue;
- private int numberOfWorkers;
-
- public void init(int numberOfWorkers) {
- log.debug("initializing workers, creating {} workers", numberOfWorkers);
- this.numberOfWorkers = numberOfWorkers;
- final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Worker-%d").build();
- this.executor = Executors.newFixedThreadPool(numberOfWorkers, threadFactory);
- this.inputQueue = new LinkedBlockingQueue<>();
- this.outputQueue = new LinkedBlockingQueue<>();
- }
-
- public void addJob(T job) {
- log.trace("job add to input queue");
- this.inputQueue.add(job);
- }
-
- public LinkedBlockingQueue<E> start() {
- for (int i = 0; i < numberOfWorkers; i++) {
- String workerName = "worker-" + i;
- log.debug("starting worker:{}", workerName);
- this.executor.submit(new Worker(workerName, this.inputQueue, this.outputQueue));
- }
- executor.shutdown();
- try {
- if (!executor.awaitTermination(TERMINATION_TIMEAUT, TimeUnit.MINUTES)) {
- log.error("timer elapsed while waiting for the worker's to finish. ");
- }
- log.debug("all workers finished");
- } catch (InterruptedException e) {
- log.error("failed while waiting for", e);
- Thread.currentThread().interrupt();
- }
- return outputQueue;
- }
-
- //
- // public static void main(String[] args) {
- // ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
- // for (int i = 0; i < 500; i++) {
- // Runnable worker = new MyRunnable(10000000L + i);
- // executor.execute(worker);
- // }
- // // This will make the executor accept no new threads
- // // and finish all existing threads in the queue
- // executor.shutdown();
- // // Wait until all threads are finish
- // executor.awaitTermination();
- // System.out.println("Finished all threads");
- // }
- // }
-}
+++ /dev/null
-/*-
- * ============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.workers;
-
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Created by michael on 6/24/2016.
- */
-public class Worker<T extends Job<E>, E> implements Runnable {
-
- private static final int QUEUE_POLL_TIMEAUT = 500;
- private String workerName;
- private LinkedBlockingQueue<T> inputQueue;
-
- private LinkedBlockingQueue<E> outputQueue;
-
- private static Logger log = Logger.getLogger(Worker.class.getName());
-
- public Worker(String workerName, LinkedBlockingQueue<T> inputQueue, LinkedBlockingQueue<E> outputQueue) {
- this.workerName = workerName;
- this.inputQueue = inputQueue;
- this.outputQueue = outputQueue;
- }
-
- @Override
- public void run() {
-
- try {
- while (true) {
- log.trace("worker:{} doing work", workerName);
- T job = inputQueue.poll(QUEUE_POLL_TIMEAUT, TimeUnit.MILLISECONDS);
- if (job == null) {
-
- log.debug("worker:{} nothing to do");
- break;
- }
- this.outputQueue.put(job.doWork());
- log.trace("worker:{} done with work", workerName);
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logInternalFlowError("executingJobFailed",
- "failed during job execution worker" + workerName, BeEcompErrorManager.ErrorSeverity.ERROR);
- log.debug("worker: {} nothing to do stoping", workerName, e);
- }
- }
-
-}