<parent>
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-main-distribution-client</artifactId>
- <version>1.1.13-SNAPSHOT</version>
+ <version>1.1.14-SNAPSHOT</version>
</parent>
<artifactId>jtosca</artifactId>
- <version>0.1.6-SNAPSHOT</version>
+ <version>0.1.7-SNAPSHOT</version>
<dependencies>
import org.openecomp.sdc.toscaparser.api.elements.constraints.Schema;
import org.openecomp.sdc.toscaparser.api.functions.Function;
import org.openecomp.sdc.toscaparser.api.utils.TOSCAVersionProperty;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
public class DataEntity {
else {
if(!(value instanceof LinkedHashMap)) {
//ERROR under investigation
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"TypeMismatchError: \"%s\" is not a map. The type is \"%s\"",
value.toString(),dataType.getType()));
for(String valueKey: valueDict.keySet()) {
//1710 devlop JSON validation
if(!("json").equals(dataType.getType()) && !allowedProps.contains(valueKey)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Data value of type \"%s\" contains unknown field \"%s\"",
dataType.getType(),valueKey));
}
}
}
if(missingProp.size() > 0) {
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"MissingRequiredFieldError: Data value of type \"%s\" is missing required field(s) \"%s\"",
dataType.getType(),missingProp.toString()));
}
}
else if (type == null) {
//NOT ANALYZED
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"MissingType: Type is missing for value \"%s\"",
value.toString()));
return value;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.*;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public abstract class EntityTemplate {
// Base class for TOSCA templates
if(type == null) {
//msg = (_('Policy definition of "%(pname)s" must have'
// ' a "type" ''attribute.') % dict(pname=name))
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValidationError: Policy definition of \"%s\" must have a \"type\" attribute",name));
}
typeDefinition = new PolicyType(type, customDef);
// '"default_instances" value is not between '
// '"min_instances" and "max_instances".' %
// self.name)
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValidationError: \"properties\" of template \"%s\": \"default_instances\" value is not between \"min_instances\" and \"max_instances\"",
name));
}
}
// Required properties found without value or a default value
if(!reqPropsNoValueOrDefault.isEmpty()) {
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"MissingRequiredFieldError: properties of template \"%s\" are missing field(s): %s",
name,reqPropsNoValueOrDefault.toString()));
}
else {
// Required properties in schema, but not in template
if(!requiredProps.isEmpty()) {
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"MissingRequiredFieldError2: properties of template \"%s\" are missing field(s): %s",
name,requiredProps.toString()));
}
@SuppressWarnings("unchecked")
private void _validateField(LinkedHashMap<String,Object> template) {
if(!(template instanceof LinkedHashMap)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: Template \"%s\" is missing required field \"%s\"",name,TYPE));
return;//???
}
bBad = (template.get(TYPE) == null);
}
if(bBad) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: Template \"%s\" is missing required field \"%s\"",name,TYPE));
}
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Section \"%s\" of template \"%s\" contains unknown field \"%s\"",section,name,sname));
}
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.Metadata;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
public class Group extends EntityTemplate {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Groups \"%s\" contains unknown field \"%s\"",
name,key));
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.TypeValidation;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.UrlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if((_path == null || _path.isEmpty()) && tpl == null) {
//msg = _('Input tosca template is not provided.')
//log.warning(msg)
- ExceptionCollector.appendException("ValidationError: Input tosca template is not provided");
+ ThreadLocalsHolder.getCollector().appendException("ValidationError: Input tosca template is not provided");
}
this.path = _path;
if(importslist == null) {
//msg = _('"imports" keyname is defined without including templates.')
//log.error(msg)
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValidationError: \"imports\" keyname is defined without including templates");
return;
}
if(importNames.contains(importName)) {
//msg = (_('Duplicate import name "%s" was found.') % import_name)
//log.error(msg)
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValidationError: Duplicate import name \"%s\" was found",importName));
}
importNames.add(importName); //???
private void _validateImportKeys(String importName, LinkedHashMap<String,Object> importUri) {
if(importUri.get(FILE) == null) {
//log.warning(_('Missing keyname "file" in import "%(name)s".') % {'name': import_name})
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: Import of template \"%s\" is missing field %s",importName,FILE));
}
for(String key: importUri.keySet()) {
//log.warning(_('Unknown keyname "%(key)s" error in '
// 'imported definition "%(def)s".')
// % {'key': key, 'def': import_name})
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Import of template \"%s\" has unknown fiels %s",importName,key));
}
}
repository = (String)((LinkedHashMap<String,Object>)importUriDef).get(REPOSITORY);
if(repository != null) {
if(!repositories.keySet().contains(repository)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidPropertyValueError: Repository \"%s\" not found in \"%s\"",
repository,repositories.keySet().toString()));
}
// 'definition "%(import_name)s".')
// % {'import_name': import_name})
//log.error(msg)
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValidationError: A template file name is not provided with import definition \"%s\"",importName));
al[0] = al[1] = null;
return al;
return al;
}
catch(IOException e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: \"%s\" loading YAML import from \"%s\"",e.getClass().getSimpleName(),fileName));
al[0] = al[1] = null;
return al;
String msg = String.format(
"ImportError: Absolute file name \"%s\" cannot be used in the URL-based input template \"%s\"",
fileName,path);
- ExceptionCollector.appendException(msg);
+ ThreadLocalsHolder.getCollector().appendException(msg);
al[0] = al[1] = null;
return al;
}
//log.error(msg)
String msg = String.format(
"ValueError: \"%s\" is not a valid file",importTemplate);
- ExceptionCollector.appendException(msg);
+ ThreadLocalsHolder.getCollector().appendException(msg);
log.debug("ImportsLoader - _loadImportTemplate - {}", msg);
}
}
else {
String msg = String.format(
"Relative file name \"%s\" cannot be used in a pre-parsed input template",fileName);
- ExceptionCollector.appendException("ImportError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("ImportError: " + msg);
al[0] = al[1] = null;
return al;
}
if(importTemplate == null || importTemplate.isEmpty()) {
//log.error(_('Import "%(name)s" is not valid.') %
// {'name': import_uri_def})
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Import \"%s\" is not valid",importUriDef));
al[0] = al[1] = null;
return al;
// for now, this must be a file
if(!aFile) {
log.error("ImportsLoader - _loadImportTemplate - Error!! Expected a file. importUriDef = {}, importTemplate = {}", importUriDef, importTemplate);
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Import \"%s\" is not a file",importName));
al[0] = al[1] = null;
return al;
return al;
}
catch(FileNotFoundException e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Failed to load YAML from \"%s\"",importName));
al[0] = al[1] = null;
return al;
}
catch(Exception e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Exception from SnakeYAML file = \"%s\"",importName));
al[0] = al[1] = null;
return al;
if(shortImportNotation) {
//log.error(_('Import "%(name)s" is not valid.') % import_uri_def)
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Import \"%s\" is not valid",importName));
al[0] = al[1] = null;
return al;
String msg = String.format(
"referenced repository \"%s\" in import definition \"%s\" not found",
repository,importName);
- ExceptionCollector.appendException("ImportError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("ImportError: " + msg);
al[0] = al[1] = null;
return al;
}
return al;
}
catch(IOException e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: Exception loading YAML import from \"%s\"",fullUrl));
al[0] = al[1] = null;
return al;
String msg = String.format(
"repository URL \"%s\" in import definition \"%s\" is not valid",
repoUrl,importName);
- ExceptionCollector.appendException("ImportError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("ImportError: " + msg);
}
// if we got here something is wrong with the flow...
log.error("ImportsLoader - _loadImportTemplate - got to dead end (importName {})", importName);
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ImportError: _loadImportTemplate got to dead end (importName %s)\n",importName));
al[0] = al[1] = null;
return al;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.*;
import org.openecomp.sdc.toscaparser.api.utils.CopyUtils;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class NodeTemplate extends EntityTemplate {
}
}
if(bFound || customDef.get(node) != null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"NotImplementedError: Lookup by TOSCA types is not supported. Requirement for \"%s\" can not be full-filled",
getName()));
return null;
}
if(templates.get(node) == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Node template \"%s\" was not found",node));
return null;
}
if(relationship == null) {
ArrayList<Object> parentReqs = ((NodeType)typeDefinition).getAllRequirements();
if(parentReqs == null) {
- ExceptionCollector.appendException("ValidationError: parent_req is null");
+ ThreadLocalsHolder.getCollector().appendException("ValidationError: parent_req is null");
}
else {
for(String key: req.keySet()) {
}
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: \"relationship\" used in template \"%s\" is missing required field \"type\"",
relatedTpl.getName()));
}
ArrayList<Object> requires = (ArrayList<Object>)((NodeType)typeDefinition).getValue(REQUIREMENTS, entityTpl, false);
if(requires != null) {
if(!(requires instanceof ArrayList)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"TypeMismatchError: \"requirements\" of template \"%s\" are not of type \"list\"",name));
}
else {
if(occurrences.size() != 2 ||
!(0 <= (int)occurrences.get(0) && (int)occurrences.get(0) <= (int)occurrences.get(1)) ||
(int)occurrences.get(1) == 0) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidPropertyValueError: property has invalid value %s",occurrences.toString()));
}
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: \"requirements\" of template \"%s\" contains unknown field \"%s\"",name,key));
}
}
_commonValidateField(value,_collectCustomIfaceOperations(iname),"interfaces");
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: \"interfaces\" of template \"%s\" contains unknown field %s",name,iname));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Node template \"%s\" has unknown field \"%s\"",name,ntname));
}
}
import java.util.Map;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
public class Policy extends EntityTemplate {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"",
name,key));
}
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.UrlUtils;
public class Repository {
if(reposit instanceof LinkedHashMap) {
url = (String)((LinkedHashMap<String,Object>)reposit).get("url");
if(url == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: Repository \"%s\" is missing required field \"url\"",
name));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: repositories \"%s\" contains unknown field \"%s\"",
keyname,key));
}
if(repositUrl != null) {
boolean urlVal = UrlUtils.validateUrl(repositUrl);
if(!urlVal) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"URLException: repsositories \"%s\" Invalid Url",keyname));
}
}
import org.openecomp.sdc.toscaparser.api.elements.PropertyDef;
import org.openecomp.sdc.toscaparser.api.parameters.Input;
import org.openecomp.sdc.toscaparser.api.parameters.Output;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class SubstitutionMappings {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: SubstitutionMappings contain unknown field \"%s\"",
key));
}
// validate the node_type of substitution mappings
String nodeType = (String)subMappingDef.get(NODE_TYPE);
if(nodeType == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: SubstitutionMappings used in topology_template is missing required field \"%s\"",
NODE_TYPE));
}
Object nodeTypeDef = customDefs.get(nodeType);
if(nodeTypeDef == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidNodeTypeError: \"%s\" is invalid",nodeType));
}
}
for(String property: requiredProperties) {
// Check property which is 'required' and has no 'default' value
if(!allInputs.contains(property)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredInputError: SubstitutionMappings with node_type \"%s\" is missing required input \"%s\"",
getNodeType(),property));
}
diffset.removeAll(allInputs);
for(String parameter: diffset) {
if(allProperties.contains(parameter)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredInputError: SubstitutionMappings with node_type \"%s\" is missing required input \"%s\"",
getNodeType(),parameter));
}
diffset = allInputs;
diffset.removeAll(allProperties);
if(diffset.contains(inp.getName()) && inp.getDefault() == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredInputError: SubstitutionMappings with node_type \"%s\" is missing rquired input \"%s\"",
getNodeType(),inp.getName()));
}
for(Output output: outputs) {
Object ado = getNodeDefinition().getAttributesDef();
if(ado != null && ((LinkedHashMap<String,Object>)ado).get(output.getName()) == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownOutputError: Unknown output \"%s\" in SubstitutionMappings with node_type \"%s\"",
output.getName(),getNodeType()));
}
import org.openecomp.sdc.toscaparser.api.functions.GetInput;
import org.openecomp.sdc.toscaparser.api.parameters.Input;
import org.openecomp.sdc.toscaparser.api.parameters.Output;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class TopologyTemplate {
DataEntity.validateDatatype("list", memberNames,null,null,null);
if(memberNames.size() < 1 ||
(new HashSet<String>(memberNames)).size() != memberNames.size()) {
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"InvalidGroupTargetException: Member nodes \"%s\" should be >= 1 and not repeated",
memberNames.toString()));
}
}
for(String member: members) {
if(!nodeNames.contains(member)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidGroupTargetException: Target member \"%s\" is not found in \"nodeTemplates\"",member));
}
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: TopologyTemplate contains unknown field \"%s\"",name));
}
}
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.common.JToscaException;
import org.openecomp.sdc.toscaparser.api.parameters.Input;
import org.openecomp.sdc.toscaparser.api.parameters.Output;
import org.openecomp.sdc.toscaparser.api.prereq.CSAR;
+import org.openecomp.sdc.toscaparser.api.utils.JToscaErrorCodes;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
private ArrayList<String> VALID_TEMPLATE_VERSIONS;
private LinkedHashMap<String,ArrayList<String>> ADDITIONAL_SECTIONS;
- private boolean bAbortOnParsingErrors = false;
private boolean isFile;
private String path;
private String inputPath;
boolean aFile,
LinkedHashMap<String,Object> yamlDictTpl) throws JToscaException {
+ ThreadLocalsHolder.setCollector(new ExceptionCollector(_path));
+
VALID_TEMPLATE_VERSIONS = new ArrayList<>();
VALID_TEMPLATE_VERSIONS.add("tosca_simple_yaml_1_0");
VALID_TEMPLATE_VERSIONS.addAll(exttools.getVersions());
//long startTime = System.nanoTime();
- //ExceptionCollector.start();
isFile = aFile;
inputPath = null;
tpl = yamlDictTpl;
}
else {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: No path or yaml_dict_tpl was provided. There is nothing to parse");
log.debug("ToscaTemplate ValueError: No path or yaml_dict_tpl was provided. There is nothing to parse");
csarTempDir = null;
}
- //ExceptionCollector.stop();
verifyTemplate();
- }
+ }
+
private void _abort() throws JToscaException {
// print out all exceptions caught
verifyTemplate();
- throw new JToscaException("jtosca aborting");
+ throw new JToscaException("jtosca aborting", JToscaErrorCodes.PATH_NOT_VALID.getValue());
}
private TopologyTemplate _topologyTemplate() {
return new TopologyTemplate(
private void _validateField() {
String sVersion = _tplVersion();
if(sVersion == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredField: Template is missing required field \"%s\"",DEFINITION_VERSION));
}
else {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Template contains unknown field \"%s\"",
sKey));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTemplateVersion: \"%s\" is invalid. Valid versions are %s",
sVersion,VALID_TEMPLATE_VERSIONS.toString()));
}
}
}
- private String _getPath(String _path) {
+ private String _getPath(String _path) throws JToscaException {
if (_path.toLowerCase().endsWith(".yaml") || _path.toLowerCase().endsWith(".yml")) {
return _path;
}
}
}
else {
- ExceptionCollector.appendException("ValueError: " + _path + " is not a valid file");
+ ThreadLocalsHolder.getCollector().appendException("ValueError: " + _path + " is not a valid file");
return null;
}
return null;
}
private void verifyTemplate() throws JToscaException {
+ ThreadLocalsHolder.getCollector().setWantTrace(false);
+
//Warnings
- List<String> warningsStrings = ExceptionCollector.getWarningsReport();
- if (warningsStrings != null && warningsStrings.size() > 0) {
- int nexcw = ExceptionCollector.warningsCaught();
+ int warningsCount = ThreadLocalsHolder.getCollector().warningsCaught();
+ if (warningsCount > 0) {
+ List<String> warningsStrings = ThreadLocalsHolder.getCollector().getWarningsReport();
log.warn("####################################################################################################");
- log.warn("ToscaTemplate - verifyTemplate - {} Parsing Warning{} occurred...", nexcw, (nexcw > 1 ? "s" : ""));
+ log.warn("CSAR Warnings found! CSAR name - {}", inputPath);
+ log.warn("ToscaTemplate - verifyTemplate - {} Parsing Warning{} occurred...", warningsCount, (warningsCount > 1 ? "s" : ""));
for (String s : warningsStrings) {
- if (s != null) {
- log.debug("ToscaTemplate - verifyTemplate - {}", s);
- }
+ log.warn("{}. CSAR name - {}", s, inputPath);
}
log.warn("####################################################################################################");
+ }
-
- List<String> exceptionStrings = ExceptionCollector.getCriticalsReport();
- if (exceptionStrings != null && exceptionStrings.size() > 0) {
- int nexc = ExceptionCollector.errorsCaught();
- log.error("####################################################################################################");
- log.error("ToscaTemplate - verifyTemplate - {} Parsing Critical{} occurred...", nexc, (nexc > 1 ? "s" : ""));
- for (String s : exceptionStrings) {
- if (s != null) {
- log.debug("ToscaTemplate - verifyTemplate - {}", s);
- }
- }
- log.error("####################################################################################################");
- if(bAbortOnParsingErrors) {
- throw new JToscaException("Aborting because of parsing errors");
- }
- }
- else {
- if (inputPath != null) {
- log.debug("ToscaTemplate - verifyTemplate - The input {} passed validation", inputPath);
- }
+ //Criticals
+ int criticalsCount = ThreadLocalsHolder.getCollector().criticalsCaught();
+ if (criticalsCount > 0) {
+ List<String> criticalStrings = ThreadLocalsHolder.getCollector().getCriticalsReport();
+ log.error("####################################################################################################");
+ log.error("ToscaTemplate - verifyTemplate - {} Parsing Critical{} occurred...", criticalsCount, (criticalsCount > 1 ? "s" : ""));
+ for (String s : criticalStrings) {
+ log.error("{}. CSAR name - {}", s, inputPath);
}
-
- }
+ throw new JToscaException(String.format("CSAR Validation Failed. CSAR name - {}. Please check logs for details.", inputPath), JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR.getValue());
+ }
}
public String getPath() {
public ArrayList<TopologyTemplate> getNestedTemplates() {
return nestedToscaTemplatesWithTopology;
}
-
- public void setAbortOnParsingErrors(boolean b) {
- bAbortOnParsingErrors = b;
- }
@Override
public String toString() {
"exttools=" + exttools +
", VALID_TEMPLATE_VERSIONS=" + VALID_TEMPLATE_VERSIONS +
", ADDITIONAL_SECTIONS=" + ADDITIONAL_SECTIONS +
- ", bAbortOnParsingErrors=" + bAbortOnParsingErrors +
", isFile=" + isFile +
", path='" + path + '\'' +
", inputPath='" + inputPath + '\'' +
import os
from copy import deepcopy
-from toscaparser.common.exception import ExceptionCollector
+from toscaparser.common.exception import ExceptionCollector.collector
from toscaparser.common.exception import InvalidTemplateVersion
from toscaparser.common.exception import MissingRequiredFieldError
from toscaparser.common.exception import UnknownFieldError
def __init__(self, path=None, parsed_params=None, a_file=True,
yaml_dict_tpl=None):
- ExceptionCollector.start()
+ ExceptionCollector.collector.start()
self.a_file = a_file
self.input_path = None
self.path = None
if yaml_dict_tpl:
self.tpl = yaml_dict_tpl
else:
- ExceptionCollector.appendException(
+ ExceptionCollector.collector.appendException(
ValueError(_('No path or yaml_dict_tpl was provided. '
'There is nothing to parse.')))
self._handle_nested_tosca_templates_with_topology()
self.graph = ToscaGraph(self.nodetemplates)
- ExceptionCollector.stop()
+ ExceptionCollector.collector.stop()
self.verify_template()
def _topology_template(self):
def _validate_field(self):
version = self._tpl_version()
if not version:
- ExceptionCollector.appendException(
+ ExceptionCollector.collector.appendException(
MissingRequiredFieldError(what='Template',
required=DEFINITION_VERSION))
else:
for name in self.tpl:
if (name not in SECTIONS and
name not in self.ADDITIONAL_SECTIONS.get(version, ())):
- ExceptionCollector.appendException(
+ ExceptionCollector.collector.appendException(
UnknownFieldError(what='Template', field=name))
def _validate_version(self, version):
if version not in self.VALID_TEMPLATE_VERSIONS:
- ExceptionCollector.appendException(
+ ExceptionCollector.collector.appendException(
InvalidTemplateVersion(
what=version,
valid_versions=', '. join(self.VALID_TEMPLATE_VERSIONS)))
self.a_file = True # the file has been decompressed locally
return os.path.join(csar.temp_dir, csar.get_main_template())
else:
- ExceptionCollector.appendException(
+ ExceptionCollector.collector.appendException(
ValueError(_('"%(path)s" is not a valid file.')
% {'path': path}))
def verify_template(self):
- if ExceptionCollector.exceptionsCaught():
+ if ExceptionCollector.collector.exceptionsCaught():
if self.input_path:
raise ValidationError(
message=(_('\nThe input "%(path)s" failed validation with '
'the following error(s): \n\n\t')
% {'path': self.input_path}) +
- '\n\t'.join(ExceptionCollector.getExceptionsReport()))
+ '\n\t'.join(ExceptionCollector.collector.getExceptionsReport()))
else:
raise ValidationError(
message=_('\nThe pre-parsed input failed validation with '
'the following error(s): \n\n\t') +
- '\n\t'.join(ExceptionCollector.getExceptionsReport()))
+ '\n\t'.join(ExceptionCollector.collector.getExceptionsReport()))
else:
if self.input_path:
msg = (_('The input "%(path)s" successfully passed '
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
public class Triggers extends EntityTemplate {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Triggers \"%s\" contains unknown field \"%s\"",
name,key));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Triggers \"%s\" contains unknown field \"%s\"",
name,key));
}
package org.openecomp.sdc.toscaparser.api;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class UnsupportedType {
public static boolean validateType(String entityType) {
for(String ust: unsupportedTypes) {
if(ust.equals(entityType)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnsupportedTypeError: Entity type \"%s\" is not supported",entityType));
return true;
}
package org.openecomp.sdc.toscaparser.api.common;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExceptionCollector {
- private static Logger log = LoggerFactory.getLogger(ExceptionCollector.class.getName());
-
- //private static boolean isCollecting = false;
- private static ArrayList<String> exceptionStrings = new ArrayList<>();
- private static ArrayList<String> exceptionTraceStrings = new ArrayList<>();
- private static ArrayList<String> warningStrings = new ArrayList<>();
- private static ArrayList<String> warningTraceStrings = new ArrayList<>();
- private static boolean bWantTrace = true;
-
- /*public static void start() {
- if(exceptionStrings == null) {
- exceptionStrings = new ArrayList<String>();
- exceptionTraceStrings = new ArrayList<String>();
- }
- isCollecting = true;
- }*/
-
- /*public static void stop() {
- isCollecting = false;
- }*/
-
- public static void clear() {
- exceptionStrings = new ArrayList<>();
- exceptionTraceStrings = new ArrayList<>();
- warningStrings = new ArrayList<>();
- warningTraceStrings = new ArrayList<>();
- }
-
- public static void appendException(String strExc) { // throws Exception {
-
- /*if(!isCollecting) {
- // throw new Exception("Can't append exception " + strExc);
- log.error("ExceptionCollector - appendException - Can't append exception {}", strExc);
- }*/
-
- if(!exceptionStrings.contains(strExc)) {
- exceptionStrings.add(strExc);
- // get stack trace
- StackTraceElement[] ste = Thread.currentThread().getStackTrace();
- StringBuilder sb = new StringBuilder();
- // skip the last 2 (getStackTrace and this)
- for(int i=2; i<ste.length; i++) {
- sb.append(String.format(" %s(%s:%d)%s",ste[i].getClassName(),ste[i].getFileName(),
- ste[i].getLineNumber(),i==ste.length-1?" ":"\n"));
- }
- exceptionTraceStrings.add(sb.toString());
- }
- }
-
- public static void appendWarning(String strExc) { // throws Exception {
-
- /*if(!isCollecting) {
- // throw new Exception("Can't append exception " + strExc);
- log.error("ExceptionCollector - appendException - Can't append exception {}", strExc);
- }*/
-
- if(!warningStrings.contains(strExc)) {
- warningStrings.add(strExc);
- // get stack trace
- StackTraceElement[] ste = Thread.currentThread().getStackTrace();
- StringBuilder sb = new StringBuilder();
- // skip the last 2 (getStackTrace and this)
- for(int i=2; i<ste.length; i++) {
- sb.append(String.format(" %s(%s:%d)%s",ste[i].getClassName(),ste[i].getFileName(),
- ste[i].getLineNumber(),i==ste.length-1?" ":"\n"));
- }
- warningTraceStrings.add(sb.toString());
- }
- }
-
- public static List<String> getCriticalsReport() {
-
- List<String> res = new ArrayList<>();
- if(exceptionStrings.size() > 0) {
- for(int i=0; i<exceptionStrings.size(); i++) {
- res.add(exceptionStrings.get(i));
- if(bWantTrace) {
- res.add(exceptionTraceStrings.get(i));
- }
- }
- }
- return res;
- }
-
- public static List<String> getWarningsReport() {
-
- List<String> res = new ArrayList<>();
- if(warningStrings.size() > 0) {
- for(int i=0; i<warningStrings.size(); i++) {
- res.add(warningStrings.get(i));
- if(bWantTrace) {
- res.add(warningTraceStrings.get(i));
- }
- }
- }
- return res;
- }
-
- public static int errorsCaught() {
- return exceptionStrings.size();
- }
-
- public static int warningsCaught() {
- return warningStrings.size();
- }
-
- public static void setWantTrace(boolean b) {
- bWantTrace = b;
- }
+ private static Logger log = LoggerFactory.getLogger(ExceptionCollector.class.getName());
+
+ private Map<String, String> notAnalyzedExceptions = new HashMap<>();
+ private Map<String, String> criticalExceptions = new HashMap<>();
+ private Map<String, String> warningExceptions = new HashMap<>();
+
+ private boolean bWantTrace = true;
+ private String filePath;
+
+ public enum ReportType {WARNING, CRITICAL, NOT_ANALYZED}
+
+ public ExceptionCollector(String filePath) {
+ this.filePath = filePath;
+ }
+
+ public void appendException(String exception) {
+
+ addException(exception, ReportType.NOT_ANALYZED);
+ }
+
+ public void appendCriticalException(String exception) {
+
+ addException(exception, ReportType.CRITICAL);
+ }
+
+ public void appendWarning(String exception) {
+
+ addException(exception, ReportType.WARNING);
+ }
+
+ private void addException(String exception, ReportType type) {
+
+ Map<String, String> exceptions = getExceptionCollection(type);
+
+ if (!exceptions.containsKey(exception)) {
+ // get stack trace
+ StackTraceElement[] ste = Thread.currentThread().getStackTrace();
+ StringBuilder sb = new StringBuilder();
+ // skip the last 2 (getStackTrace and this)
+ for (int i = 2; i < ste.length; i++) {
+ sb.append(String.format(" %s(%s:%d)%s", ste[i].getClassName(), ste[i].getFileName(),
+ ste[i].getLineNumber(), i == ste.length - 1 ? " " : "\n"));
+ }
+ exceptions.put(exception, sb.toString());
+ }
+ }
+
+ public List<String> getCriticalsReport() {
+
+ return getReport(ReportType.CRITICAL);
+ }
+
+ public List<String> getNotAnalyzedExceptionsReport() {
+
+ return getReport(ReportType.NOT_ANALYZED);
+ }
+
+ public List<String> getWarningsReport() {
+
+ return getReport(ReportType.WARNING);
+ }
+
+ private List<String> getReport(ReportType type) {
+ Map<String, String> collectedExceptions = getExceptionCollection(type);
+
+ List<String> report = new ArrayList<>();
+ if (collectedExceptions.size() > 0) {
+ for (Map.Entry<String, String> exception : collectedExceptions.entrySet()) {
+ report.add(exception.getKey());
+ if (bWantTrace) {
+ report.add(exception.getValue());
+ }
+ }
+ }
+
+ return report;
+ }
+
+ private Map<String, String> getExceptionCollection(ReportType type) {
+ switch (type) {
+ case WARNING:
+ return warningExceptions;
+ case CRITICAL:
+ return criticalExceptions;
+ case NOT_ANALYZED:
+ return notAnalyzedExceptions;
+ default:
+ return notAnalyzedExceptions;
+ }
+ }
+
+ public int errorsNotAnalyzedCaught() {
+ return notAnalyzedExceptions.size();
+ }
+
+ public int criticalsCaught() {
+ return criticalExceptions.size();
+ }
+
+ public int warningsCaught() {
+ return warningExceptions.size();
+ }
+
+ public void setWantTrace(boolean b) {
+ bWantTrace = b;
+ }
}
public class JToscaException extends Exception {
private static final long serialVersionUID = 1L;
-
- public JToscaException(String message) {
+ private String code;
+
+ public JToscaException(String message, String code) {
super(message);
+ this.code = code;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
}
+ //JT1001 - Meta file missing
+ //JT1002 - Invalid yaml content
+ //JT1003 - Entry-Definition not defined in meta file
+ //JT1004 - Entry-Definition file missing
+ //JT1005 - General Error
+ //JT1006 - General Error/Path not valid
}
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GroupType extends StatefulEntityType {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Group Type \"%s\" contains unknown field \"%s\"",
groupType,name));
}
private void _validateMetadata(LinkedHashMap<String,Object> metadata) {
String mtt = (String) metadata.get("type");
if(mtt != null && !mtt.equals("map") && !mtt.equals("tosca:map")) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" defined in group for metadata is invalid",
mtt));
}
if(estob instanceof LinkedHashMap) {
String est = (String)((LinkedHashMap<String,Object>)estob).get("type");
if(!est.equals("string")) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" defined in group for metadata \"%s\" is invalid",
est,entrySchema));
}
import org.openecomp.sdc.toscaparser.api.EntityTemplate;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class InterfacesDef extends StatefulEntityType {
inputs = (LinkedHashMap<String,Object>)me.getValue();
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: \"interfaces\" of template \"%s\" contain unknown field \"%s\"",
nodeTemplate.getName(),me.getKey()));
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.InterfacesDef;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class NodeType extends StatefulEntityType {
// TOSCA built-in node type
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Nodetype \"%s\" has unknown field \"%s\"",ntype,key));
}
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.utils.TOSCAVersionProperty;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class PolicyType extends StatefulEntityType {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Policy \"%s\" contains unknown field \"%s\"",
type,key));
}
LinkedHashMap<String,Object> _customDef) {
for(String nodetype: _targetsList) {
if(_customDef.get(nodetype) == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" defined in targets for policy \"%s\"",
nodetype,type));
private void _validateMetadata(LinkedHashMap<String,Object> _metaData) {
String mtype = (String)_metaData.get("type");
if(mtype != null && !mtype.equals("map") && !mtype.equals("tosca:map")) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" defined in policy for metadata",
mtype));
}
String est = (String)
((LinkedHashMap<String,Object>)estob).get("type");
if(!est.equals("string")) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" defined in policy for metadata \"%s\"",
est,entrySchema));
}
import org.openecomp.sdc.toscaparser.api.DataEntity;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
public class PortSpec {
// verify one of the specified values is set
if(source == null && sourceRange == null &&
target == null && targetRange == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeAdditionalRequirementsError: Additional requirements for type \"%s\" not met",
TYPE_URI));
}
}
}
catch(Exception e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" do not meet requirements for type \"%s\"",
_properties.toString(),SHORTNAME));
}
import java.util.Map;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class PropertyDef {
if(schema.get("type") == null) {
//msg = (_('Schema definition of "%(pname)s" must have a "type" '
// 'attribute.') % dict(pname=self.name))
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute",name));
}
_loadRequiredAttrFromSchema();
// attr,
// value,
// valid_values)
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"Schema definition of \"%s\" has \"required\" attribute with an invalid value",
name));
}
// attr,
// value,
// valid_values)
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"Schema definition of \"%s\" has \"status\" attribute with an invalid value",
name));
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.EntityType;
import org.openecomp.sdc.toscaparser.api.elements.StatefulEntityType;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class RelationshipType extends StatefulEntityType {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Relationshiptype \"%s\" has unknown field \"%s\"",type,key));
}
}
import java.util.regex.Pattern;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return key;
}
}
- ExceptionCollector.appendWarning(String.format(
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"'The unit \"%s\" is not valid. Valid units are \n%s",
inputUnit,SCALAR_UNIT_DICT.keySet().toString()));
return inputUnit;
value = matcher.group(1) + " " + scalarUnit;
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid scalar-unit",value.toString()));
}
return value;
if(type.equals(SCALAR_UNIT_FREQUENCY)) {
return (new ScalarUnitFrequency(value)).getNumFromScalarUnit(unit);
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"TypeError: \"%s\" is not a valid scalar-unit type",type));
return 0.0;
}
import org.openecomp.sdc.toscaparser.api.elements.AttributeDef;
import org.openecomp.sdc.toscaparser.api.elements.EntityType;
import org.openecomp.sdc.toscaparser.api.elements.PropertyDef;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class StatefulEntityType extends EntityType {
}
else{
defs = null;
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTypeError: \"%s\" is not a valid type",entityType));
}
}
Object to = me.getValue();
if(to == null || !(to instanceof LinkedHashMap)) {
String s = to == null ? "null" : to.getClass().getSimpleName();
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"Unexpected type error: property \"%s\" has type \"%s\" (expected dict)",pdname,s));
continue;
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.extensions.ExtTools;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class TypeValidation {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Template \"%s\" contains unknown field \"%s\"",
importDef.toString(),name));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTemplateVersion: version \"%s\" in \"%s\" is not supported\n" +
"Allowed versions: [%s]",
sVersion,importDef.toString(),allowed));
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.ScalarUnit;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public abstract class Constraint {
if(!(constraint instanceof LinkedHashMap) ||
((LinkedHashMap<String,Object>)constraint).size() != 1) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"InvalidSchemaError: Invalid constraint schema " + constraint.toString());
}
return new Pattern(propname,proptype,constraint);
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidSchemaError: Invalid property \"%s\"",constraintClass));
return null;
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidSchemaError: Property \"%s\" is not valid for data type \"%s\"",
constraintKey,propertyType));
}
value = ScalarUnit.getScalarunitValue(propertyType,value,null);
}
if(!_isValid(value)) {
- ExceptionCollector.appendWarning("ValidationError: " + _errMsg(value));
+ ThreadLocalsHolder.getCollector().appendWarning("ValidationError: " + _errMsg(value));
}
}
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.functions.Function;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GreaterOrEqual extends Constraint {
// Constraint class for "greater_or_equal"
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"greater_or_equal\" expects comparable values");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"greater_or_equal\" expects comparable values");
}
}
super(GreaterOrEqual, self).__init__(property_name, property_type,
constraint)
if not isinstance(self.constraint_value, self.valid_types):
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
InvalidSchemaError(message=_('The property '
'"greater_or_equal" expects '
'comparable values.')))
import java.util.Date;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GreaterThan extends Constraint {
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"greater_than\" expects comparable values");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"greater_than\" expects comparable values");
}
}
import java.util.Date;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import java.util.ArrayList;
super(name,type,c);
if(!(constraintValue instanceof ArrayList) || ((ArrayList<Object>)constraintValue).size() != 2) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"in_range\" expects a list");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"in_range\" expects a list");
}
String msg = "The property \"in_range\" expects comparable values";
for(Object vo: alcv) {
if(!validTypes.contains(vo.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: " + msg);
}
// The only string we allow for range is the special value 'UNBOUNDED'
if((vo instanceof String) && !((String)vo).equals(UNBOUNDED)) {
- ExceptionCollector.appendException("InvalidSchemaError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: " + msg);
}
}
min = alcv.get(0);
package org.openecomp.sdc.toscaparser.api.elements.constraints;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Length extends Constraint {
// Constraint class for "length"
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"length\" expects an integer");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"length\" expects an integer");
}
}
import java.util.Date;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class LessOrEqual extends Constraint {
// Constraint class for "less_or_equal"
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"less_or_equal\" expects comparable values");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"less_or_equal\" expects comparable values");
}
}
import java.util.Date;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class LessThan extends Constraint {
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"less_than\" expects comparable values");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"less_than\" expects comparable values");
}
}
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class MaxLength extends Constraint {
// Constraint class for "min_length"
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"max_length\" expects an integer");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"max_length\" expects an integer");
}
}
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class MinLength extends Constraint {
// Constraint class for "min_length"
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"min_length\" expects an integer");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"min_length\" expects an integer");
}
}
import java.util.regex.PatternSyntaxException;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Pattern extends Constraint {
super(name,type,c);
if(!validTypes.contains(constraintValue.getClass().getSimpleName())) {
- ExceptionCollector.appendException("InvalidSchemaError: The property \"pattern\" expects a string");
+ ThreadLocalsHolder.getCollector().appendException("InvalidSchemaError: The property \"pattern\" expects a string");
}
}
protected boolean _isValid(Object value) {
try {
if(!(value instanceof String)) {
- ExceptionCollector.appendException(String.format("ValueError: Input value \"%s\" to \"pattern\" property \"%s\" must be a string",
+ ThreadLocalsHolder.getCollector().appendException(String.format("ValueError: Input value \"%s\" to \"pattern\" property \"%s\" must be a string",
value.toString(),propertyName));
return false;
}
return false;
}
catch(PatternSyntaxException pse) {
- ExceptionCollector.appendException(String.format("ValueError: Invalid regex \"%s\" in \"pattern\" property \"%s\"",
+ ThreadLocalsHolder.getCollector().appendException(String.format("ValueError: Invalid regex \"%s\" in \"pattern\" property \"%s\"",
constraintValue.toString(),propertyName));
return false;
}
import java.util.Map;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Schema {
if(!(_schemaDict instanceof LinkedHashMap)) {
//msg = (_('Schema definition of "%(pname)s" must be a dict.')
// % dict(pname=name))
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidSchemaError: Schema definition of \"%s\" must be a dict",name));
}
if(_schemaDict.get("type") == null) {
//msg = (_('Schema definition of "%(pname)s" must have a "type" '
// 'attribute.') % dict(pname=name))
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidSchemaError: Schema definition of \"%s\" must have a \"type\" attribute",name));
}
}
else {
// error
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Constraint type \"%s\" for property \"%s\" is not supported",
cClass,name));
}
import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Concat extends Function {
// Validate the function and provide an instance of the function
@Override
void validate() {
if(args.size() < 1) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Invalid arguments for function \"concat\". " +
"Expected at least one argument");
}
import java.util.ArrayList;
import java.util.LinkedHashMap;
-import org.openecomp.sdc.toscaparser.api.Capability;
-import org.openecomp.sdc.toscaparser.api.EntityTemplate;
-import org.openecomp.sdc.toscaparser.api.NodeTemplate;
-import org.openecomp.sdc.toscaparser.api.RelationshipTemplate;
-import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
+import org.openecomp.sdc.toscaparser.api.*;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.AttributeDef;
import org.openecomp.sdc.toscaparser.api.elements.CapabilityTypeDef;
import org.openecomp.sdc.toscaparser.api.elements.RelationshipType;
import org.openecomp.sdc.toscaparser.api.elements.StatefulEntityType;
import org.openecomp.sdc.toscaparser.api.elements.constraints.Schema;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GetAttribute extends Function {
// Get an attribute value of an entity defined in the service template
@Override
void validate() {
if(args.size() < 2) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Illegal arguments for function \"get_attribute\". Expected arguments: \"node-template-name\", \"req-or-cap\" (optional), \"property name.\"");
return;
}
for(Object elem: args.subList(index,args.size())) {
if(valueType.equals("list")) {
if(!(elem instanceof Integer)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Illegal arguments for function \"get_attribute\" \"%s\". Expected positive integer argument",
elem.toString()));
}
}
}
if(bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: 'Illegal arguments for function \"get_attribute\". Unexpected attribute/index value \"%d\"",
elem));
return;
valueType = (String)prop.getSchema().get("type");
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Illegal arguments for function \"get_attribute\". Attribute name \"%s\" not found in \"%\"",
elem,valueType));
}
if(nodeTpl != null &&
!_attributeExistsInType(nodeTpl.getTypeDefinition()) &&
!nodeTpl.getProperties().keySet().contains(getAttributeName())) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Attribute \"%s\" was not found in node template \"%s\"",
getAttributeName(),nodeTpl.getName()));
}
// Currently this is the only way to tell whether the function
// is used within the outputs section of the TOSCA template.
if(context instanceof ArrayList) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: \"get_attribute: [ HOST, ... ]\" is not allowed in \"outputs\" section of the TOSCA template");
return null;
}
NodeTemplate nodeTpl = _findHostContainingAttribute(SELF);
if(nodeTpl == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"get_attribute: [ HOST, ... ]\" was used in " +
"node template \"%s\" but \"%s\" was not found in " +
"the relationship chain",((NodeTemplate)context).getName(),HOSTED_ON));
}
if(nodeTemplateName.equals(TARGET)) {
if(!(((EntityTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"TARGET\" keyword can only be used in context " +
" to \"Relationships\" target node");
return null;
}
if(nodeTemplateName.equals(SOURCE)) {
if(!(((EntityTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"SOURCE\" keyword can only be used in context " +
" to \"Relationships\" source node");
return null;
return nt;
}
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Node template \"%s\" was not found",nodeTemplateName));
return null;
}
attribute = attrs.get(attrName);
}
if(attribute == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Attribute \"%s\" was not found in capability \"%s\" of node template \"%s\" referenced from node template \"%s\"",
attrName,capabilityName,nodeTemplate.getName(),((NodeTemplate)context).getName()));
}
String msg = String.format(
"Requirement/Capability \"%s\" referenced from node template \"%s\" was not found in node template \"%s\"",
capabilityName,((NodeTemplate)context).getName(),nodeTemplate.getName());
- ExceptionCollector.appendException("KeyError: " + msg);
+ ThreadLocalsHolder.getCollector().appendException("KeyError: " + msg);
return null;
}
import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.parameters.Input;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GetInput extends Function {
@Override
void validate() {
if(args.size() != 1) {
- //ERROR under investigation
- ExceptionCollector.appendWarning(String.format(
+ //PA - changed to WARNING from CRITICAL after talking to Renana, 22/05/2017
+ ThreadLocalsHolder.getCollector().appendWarning(String.format(
"ValueError: Expected one argument for function \"get_input\" but received \"%s\"",
args.toString()));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownInputError: Unknown input \"%s\"",args.get(0)));
}
}
import java.util.ArrayList;
-import org.openecomp.sdc.toscaparser.api.EntityTemplate;
-import org.openecomp.sdc.toscaparser.api.NodeTemplate;
-import org.openecomp.sdc.toscaparser.api.RelationshipTemplate;
-import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
+import org.openecomp.sdc.toscaparser.api.*;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.InterfacesDef;
import org.openecomp.sdc.toscaparser.api.elements.RelationshipType;
import org.openecomp.sdc.toscaparser.api.elements.StatefulEntityType;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GetOperationOutput extends Function {
_findOperationName(interfaceName,(String)args.get(2));
}
else {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Illegal arguments for function \"get_operation_output\". " +
"Expected arguments: \"template_name\",\"interface_name\"," +
"\"operation_name\",\"output_variable_name\"");
return _interfaceName;
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: invalid interface name \"%s\" in \"get_operation_output\"",
_interfaceName));
return null;
return operationName;
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Invalid operation of Configure interface \"%s\" in \"get_operation_output\"",
operationName));
return null;
return operationName;
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Invalid operation of Configure interface \"%s\" in \"get_operation_output\"",
operationName));
return null;
}
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Invalid interface name \"%s\" in \"get_operation_output\"",
interfaceName));
return null;
private NodeTemplate _findNodeTemplate(String nodeTemplateName) {
if(nodeTemplateName.equals(TARGET)) {
if(!(((EntityTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"TARGET\" keyword can only be used in context " +
" to \"Relationships\" target node");
return null;
}
if(nodeTemplateName.equals(SOURCE)) {
if(!(((EntityTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"SOURCE\" keyword can only be used in context " +
" to \"Relationships\" source node");
return null;
return nt;
}
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Node template \"%s\" was not found",nodeTemplateName));
return null;
}
import java.util.ArrayList;
import java.util.LinkedHashMap;
-import org.openecomp.sdc.toscaparser.api.Capability;
-import org.openecomp.sdc.toscaparser.api.NodeTemplate;
-import org.openecomp.sdc.toscaparser.api.Property;
-import org.openecomp.sdc.toscaparser.api.RelationshipTemplate;
-import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
+import org.openecomp.sdc.toscaparser.api.*;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.elements.CapabilityTypeDef;
import org.openecomp.sdc.toscaparser.api.elements.EntityType;
import org.openecomp.sdc.toscaparser.api.elements.PropertyDef;
import org.openecomp.sdc.toscaparser.api.elements.RelationshipType;
import org.openecomp.sdc.toscaparser.api.elements.StatefulEntityType;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class GetProperty extends Function {
// Get a property value of an entity defined in the same service template
@Override
void validate() {
if(args.size() < 2) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Illegal arguments for function \"get_property\". Expected arguments: \"node-template-name\", \"req-or-cap\" (optional), \"property name.\"");
return;
}
property = ((Property)props.get(propertyName)).getValue();
}
if(property == null && throwErrors) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" was not found in capability \"%s\" of node template \"%s\" referenced from node template \"%s\"",
propertyName,capabilityName,nodeTemplate.getName(),((NodeTemplate)context).getName()));
}
return property;
}
if(throwErrors) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Requirement/Capability \"%s\" referenced from node template \"%s\" was not found in node template \"%s\"",
capabilityName,((NodeTemplate)context).getName(),nodeTemplate.getName()));
}
LinkedHashMap<String,Property> props = nodeTpl.getProperties();
Property found = props.get(propertyName);
if(found == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" was not found in node template \"%s\"",
propertyName,nodeTpl.getName()));
}
if(nodeTemplateName.equals(HOST)) {
NodeTemplate node = _findHostContainingProperty(null);
if(node == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" was not found in capability \"%s\" of node template \"%s\" referenced from node template \"%s\"",
(String)args.get(2),(String)args.get(1),((NodeTemplate)context).getName()));
return null;
}
if(nodeTemplateName.equals(TARGET)) {
if(!(((RelationshipTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"TARGET\" keyword can only be used in context to \"Relationships\" target node");
return null;
}
}
if(nodeTemplateName.equals(SOURCE)) {
if(!(((RelationshipTemplate)context).getTypeDefinition() instanceof RelationshipType)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"KeyError: \"SOURCE\" keyword can only be used in context to \"Relationships\" target node");
return null;
}
return nodeTemplate;
}
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Node template \"%s\" was not found. Referenced from Node Template \"%s\"",
nodeTemplateName,((NodeTemplate)context).getName()));
return ((ArrayList)value).get(index);
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" found in capability \"%s\" referenced from node template \"%s\" must have an element with index %d",
args.get(2),args.get(1),((NodeTemplate)context).getName(),index));
}
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" found in capability \"%s\" referenced from node template \"%s\" must be a list",
args.get(2),args.get(1),((NodeTemplate)context).getName()));
}
return ov;
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" found in capability \"%s\" referenced from node template \"%s\" must have an attribute named \"%s\"",
args.get(2),args.get(1),((NodeTemplate)context).getName(),attribute));
}
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"KeyError: Property \"%s\" found in capability \"%s\" referenced from node template \"%s\" must be a dict",
args.get(2),args.get(1),((NodeTemplate)context).getName()));
}
import org.openecomp.sdc.toscaparser.api.NodeTemplate;
import org.openecomp.sdc.toscaparser.api.TopologyTemplate;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Token extends Function {
// Validate the function and provide an instance of the function
@Override
void validate() {
if(args.size() < 3) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Invalid arguments for function \"token\". " +
"Expected at least three arguments");
}
else {
if(!(args.get(1) instanceof String) ||
((String)args.get(1)).length() != 1) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Invalid arguments for function \"token\". " +
"Expected single char value as second argument");
}
if(!(args.get(2) instanceof Integer)) {
- ExceptionCollector.appendException(
+ ThreadLocalsHolder.getCollector().appendException(
"ValueError: Invalid arguments for function \"token\"" +
"Expected integer value as third argument");
}
import org.openecomp.sdc.toscaparser.api.elements.EntityType;
import org.openecomp.sdc.toscaparser.api.elements.constraints.Constraint;
import org.openecomp.sdc.toscaparser.api.elements.constraints.Schema;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Input {
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Input \"%s\" contains unknown field \"%s\"",
name,key));
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Invalid type \"%s\"",inputType));
}
}
import java.util.LinkedHashMap;
import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
public class Output {
private void _validateField() {
if(!(attrs instanceof LinkedHashMap)) {
//TODO wrong error message...
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValidationError: Output \"%s\" has wrong type. Expecting a dict",
name));
}
if(getValue() == null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"MissingRequiredFieldError: Output \"%s\" is missing required \"%s\"",
name,VALUE));
}
}
}
if(!bFound) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"UnknownFieldError: Output \"%s\" contains unknown field \"%s\"",
name,key));
}
import java.util.zip.ZipInputStream;
import org.openecomp.sdc.toscaparser.api.ImportsLoader;
-import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
-import org.openecomp.sdc.toscaparser.api.elements.Metadata;
+import org.openecomp.sdc.toscaparser.api.common.JToscaException;
+import org.openecomp.sdc.toscaparser.api.utils.JToscaErrorCodes;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.openecomp.sdc.toscaparser.api.utils.UrlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@SuppressWarnings("unchecked")
- public boolean validate() {
+ public boolean validate() throws JToscaException {
isValidated = true;
//validate that the file or URL exists
if(isFile) {
File f = new File(path);
if (!f.isFile()) {
- ExceptionCollector.appendException(String.format("\"%s\" is not a file", path));
+ ThreadLocalsHolder.getCollector().appendException(String.format("\"%s\" is not a file", path));
return false;
}
else {
}
else {
if(!UrlUtils.validateUrl(path)) {
- ExceptionCollector.appendException(String.format("ImportError: \"%s\" does not exist",path));
+ ThreadLocalsHolder.getCollector().appendException(String.format("ImportError: \"%s\" does not exist",path));
return false;
}
// get it to a local file
Files.copy(in,ptf,StandardCopyOption.REPLACE_EXISTING);
}
catch(Exception e) {
- ExceptionCollector.appendException("ImportError: failed to load CSAR from " + path);
+ ThreadLocalsHolder.getCollector().appendException("ImportError: failed to load CSAR from " + path);
return false;
}
}
- private void _parseAndValidateMetaProperties() {
+ private void _parseAndValidateMetaProperties() throws JToscaException {
ZipFile zf = null;
raf.close();
// check if Zip's magic number
if (n != 0x504B0304) {
- throw new IOException(String.format("\"%s\" is not a valid zip file", csar));
+ String errorString = String.format("\"%s\" is not a valid zip file", csar);
+ log.error(errorString);
+ throw new JToscaException(errorString , JToscaErrorCodes.INVALID_CSAR_FORMAT.getValue());
}
// validate that it contains the metadata file in the correct location
zf = new ZipFile(csar);
ZipEntry ze = zf.getEntry("TOSCA-Metadata/TOSCA.meta");
if (ze == null) {
- throw new IOException(String.format(
+
+ String errorString = String.format(
"\"%s\" is not a valid CSAR as it does not contain the " +
- "required file \"TOSCA.meta\" in the folder \"TOSCA-Metadata\"", csar));
+ "required file \"TOSCA.meta\" in the folder \"TOSCA-Metadata\"", csar);
+ log.error(errorString);
+ throw new JToscaException(errorString, JToscaErrorCodes.MISSING_META_FILE.getValue());
}
//Going over expected metadata files and parsing them
if (ze != null) {
InputStream inputStream = zf.getInputStream(ze);
n = inputStream.read(ba, 0, 4096);
-
String md = new String(ba);
md = md.substring(0, (int) n);
- Yaml yaml = new Yaml();
- Object mdo = yaml.load(md);
- if (!(mdo instanceof LinkedHashMap)) {
- throw new IOException(String.format(
- "The file \"%s\" in the" +
- " CSAR \"%s\" does not contain valid YAML content", ze.getName(), csar));
+
+ String errorString = String.format(
+ "The file \"%s\" in the" +
+ " CSAR \"%s\" does not contain valid YAML content", ze.getName(), csar);
+
+ try {
+ Yaml yaml = new Yaml();
+ Object mdo = yaml.load(md);
+ if (!(mdo instanceof LinkedHashMap)) {
+ log.error(errorString);
+ throw new JToscaException(errorString, JToscaErrorCodes.INVALID_META_YAML_CONTENT.getValue());
+ }
+
+ String[] split = ze.getName().split("/");
+ String fileName = split[split.length - 1];
+
+ if (!metaProperties.containsKey(fileName)) {
+ metaProperties.put(fileName, (LinkedHashMap<String, Object>) mdo);
+ }
}
-
- String[] split = ze.getName().split("/");
- String fileName = split[split.length - 1];
-
- if (!metaProperties.containsKey(fileName)) {
- metaProperties.put(fileName, (LinkedHashMap<String, Object>) mdo);
+ catch(Exception e) {
+ log.error(errorString);
+ throw new JToscaException(errorString, JToscaErrorCodes.INVALID_META_YAML_CONTENT.getValue());
}
}
}
// verify it has "Entry-Definition"
String edf = _getMetadata("Entry-Definitions");
if (edf == null) {
- throw new IOException(String.format(
+ String errorString = String.format(
"The CSAR \"%s\" is missing the required metadata " +
- "\"Entry-Definitions\" in \"TOSCA-Metadata/TOSCA.meta\"", csar));
+ "\"Entry-Definitions\" in \"TOSCA-Metadata/TOSCA.meta\"", csar);
+ log.error(errorString);
+ throw new JToscaException(errorString, JToscaErrorCodes.ENTRY_DEFINITION_NOT_DEFINED.getValue());
}
//validate that "Entry-Definitions' metadata value points to an existing file in the CSAR
}
}
if (!foundEDF) {
- throw new IOException(String.format(
- "The \"Entry-Definitions\" file defined in the CSAR \"%s\" does not exist", csar));
+ String errorString = String.format(
+ "The \"Entry-Definitions\" file defined in the CSAR \"%s\" does not exist", csar);
+ log.error(errorString);
+ throw new JToscaException(errorString, JToscaErrorCodes.MISSING_ENTRY_DEFINITION_FILE.getValue());
}
+ } catch (JToscaException e) {
+ //ThreadLocalsHolder.getCollector().appendCriticalException(e.getMessage());
+ throw e;
} catch (Exception e) {
- ExceptionCollector.appendException("ValidationError: " + e.getMessage());
+ ThreadLocalsHolder.getCollector().appendException("ValidationError: " + e.getMessage());
errorCaught = true;
}
}
}
- private String _getMetadata(String key) {
+ private String _getMetadata(String key) throws JToscaException {
if(!isValidated) {
validate();
}
return value != null ? value.toString() : null;
}
- public String getAuthor() {
+ public String getAuthor() throws JToscaException {
return _getMetadata("Created-By");
}
- public String getVersion() {
+ public String getVersion() throws JToscaException {
return _getMetadata("CSAR-Version");
}
return metaProperties.get(propertiesFile);
}
- public String getMainTemplate() {
+ public String getMainTemplate() throws JToscaException {
String entryDef = _getMetadata("Entry-Definitions");
ZipFile zf;
boolean ok = false;
}
@SuppressWarnings("unchecked")
- public LinkedHashMap<String,Object> getMainTemplateYaml() {
+ public LinkedHashMap<String,Object> getMainTemplateYaml() throws JToscaException {
String mainTemplate = tempDir + File.separator + getMainTemplate();
if(mainTemplate != null) {
try {
return (LinkedHashMap<String,Object>)data;
}
catch(Exception e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"The file \"%s\" in the CSAR \"%s\" does not " +
"contain valid TOSCA YAML content",
mainTemplate,csar));
return null;
}
- public String getDescription() {
+ public String getDescription() throws JToscaException {
String desc = _getMetadata("Description");
if(desc != null) {
return desc;
return tempDir;
}
- public void decompress() throws IOException {
+ public void decompress() throws IOException, JToscaException {
if(!isValidated) {
validate();
}
}
- private void _validateExternalReferences() {
+ private void _validateExternalReferences() throws JToscaException {
// Extracts files referenced in the main template
// These references are currently supported:
// * imports
}
}
else {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Unexpected artifact definition for \"%s\"",
artifactKey));
errorCaught = true;
return;
}
else {
- ExceptionCollector.appendException(msg);
+ ThreadLocalsHolder.getCollector().appendException(msg);
errorCaught = true;
}
}
catch (Exception e) {
- ExceptionCollector.appendException(msg);
+ ThreadLocalsHolder.getCollector().appendException(msg);
}
}
}
if(raiseExc) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: The resource \"%s\" does not exist",resourceFile));
}
errorCaught = true;
--- /dev/null
+package org.openecomp.sdc.toscaparser.api.utils;
+
+
+public enum JToscaErrorCodes {
+ MISSING_META_FILE("JT1001"),
+ INVALID_META_YAML_CONTENT("JT1002"),
+ ENTRY_DEFINITION_NOT_DEFINED("JT1003"),
+ MISSING_ENTRY_DEFINITION_FILE ("JT1004"),
+ GENERAL_ERROR("JT1005"),
+ PATH_NOT_VALID("JT1006"),
+ CSAR_TOSCA_VALIDATION_ERROR("JT1007"),
+ INVALID_CSAR_FORMAT("JT1008");
+
+ private String value;
+
+ private JToscaErrorCodes(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static JToscaErrorCodes getByCode(String code) {
+ for(JToscaErrorCodes v : values()){
+ if( v.getValue().equals(code)){
+ return v;
+ }
+ }
+ return null;
+ }
+}
\ No newline at end of file
Pattern pattern = Pattern.compile(versionRe);
Matcher matcher = pattern.matcher(version);
if(!matcher.find()) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTOSCAVersionPropertyException: " +
"Value of TOSCA version property \"%s\" is invalid",
version));
if((fixVersion == null && value != null) ||
(minorVersion.equals("0") && majorVersion.equals("0") &&
fixVersion.equals("0") && value != null)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTOSCAVersionPropertyException: " +
"Value of TOSCA version property \"%s\" is invalid",
version));
// Eg: version = 18.0.0-1 is invalid.
if(qualifier == null && value != null) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"InvalidTOSCAVersionPropertyException: " +
"Value of TOSCA version property \"%s\" is invalid",
version));
--- /dev/null
+package org.openecomp.sdc.toscaparser.api.utils;
+
+import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
+
+public class ThreadLocalsHolder {
+
+ private static final ThreadLocal<ExceptionCollector> exceptionCollectorThreadLocal = new ThreadLocal<>();
+
+ private ThreadLocalsHolder(){}
+
+ public static ExceptionCollector getCollector() {
+ return exceptionCollectorThreadLocal.get();
+ }
+
+ public static void setCollector(ExceptionCollector exceptionCollector) {
+ cleanup();
+ exceptionCollectorThreadLocal.set(exceptionCollector);
+ }
+
+ public static void cleanup(){
+ exceptionCollectorThreadLocal.remove();
+ }
+
+}
// relative_path: heat-translator
// - joined: http://www.githib.com/openstack/heat-translator
if(!validateUrl(sUrl)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: The URL \"%s\" is malformed",sUrl));
}
try {
return (new URL(base,relativePath)).toString();
}
catch(MalformedURLException e) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: Joining URL \"%s\" and relative path \"%s\" caused an exception",sUrl,relativePath));
return sUrl;
}
public static Object validateNumeric(Object value) {
if(!(value instanceof Number)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a numeric",value.toString()));
}
return value;
if(value instanceof Boolean) {
return (Boolean)value ? 1 : 0;
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not an integer",value.toString()));
}
return value;
public static Object validateFloat(Object value) {
if(!(value instanceof Float || value instanceof Double)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a float",value.toString()));
}
return value;
public static Object validateString(Object value) {
if(!(value instanceof String)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \'%s\' is not a string",value.toString()));
}
return value;
public static Object validateList(Object value) {
if(!(value instanceof ArrayList)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a list",value.toString()));
}
return value;
validateList(range);
// validate range list has a min and max
if(range instanceof ArrayList && ((ArrayList<Object>)range).size() != 2) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid range",range.toString()));
// too dangerous to continue...
return range;
if(!(r0 instanceof Integer) && !(r0 instanceof Float) ||
!(r1 instanceof Integer) && !(r1 instanceof Float)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid range",range.toString()));
// too dangerous to continue...
return range;
if(!minTest && !maxTest) {
// Note: min == max is allowed
if(min > max) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError:\"%s\" is not a valid range",range.toString()));
}
}
public static Object validateValueInRange(Object value,Object range,String propName) {
// verify all 3 are numeric and convert to Floats
if(!(value instanceof Integer || value instanceof Float)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: validateInRange: \"%s\" is not a number",range.toString()));
return value;
}
// better safe than sorry...
// validate that range list has a min and max
if(range instanceof ArrayList && ((ArrayList<Object>)range).size() != 2) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid range",range.toString()));
// too dangerous to continue...
return value;
if(!(r0 instanceof Integer) && !(r0 instanceof Float) ||
!(r1 instanceof Integer) && !(r1 instanceof Float)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid range",range.toString()));
// too dangerous to continue...
return value;
if(!minTest && !maxTest) {
// Note: min == max is allowed
if(min > max) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError:\"%s\" is not a valid range",range.toString()));
}
}
}
}
if(bError) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"RangeValueError: Property \"%s\", \"%s\" not in range [\"%s\" - \"%s\"",
propName,value.toString(),r0.toString(),r1.toString()));
}
public static Object validateMap(Object ob) {
if(!(ob instanceof LinkedHashMap)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError\"%s\" is not a map.",ob.toString()));
}
return ob;
return normalized.equals("true");
}
}
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a boolean",value.toString()));
return value;
}
// timestamps are loaded as Date objects by the YAML parser
if(!(value instanceof Date)) {
- ExceptionCollector.appendException(String.format(
+ ThreadLocalsHolder.getCollector().appendException(String.format(
"ValueError: \"%s\" is not a valid timestamp",
value.toString()));
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-main-distribution-client</artifactId>
- <version>1.1.13-SNAPSHOT</version>
+ <version>1.1.14-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<parent>
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-main-distribution-client</artifactId>
- <version>1.1.13-SNAPSHOT</version>
+ <version>1.1.14-SNAPSHOT</version>
</parent>
<artifactId>sdc-distribution-ci</artifactId>
import java.util.Date;\r
import java.util.List;\r
\r
-import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;\r
+import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;\r
+import org.openecomp.sdc.tosca.parser.impl.SdcPropertyNames;\r
import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory;\r
-import org.openecomp.sdc.toscaparser.api.NodeTemplate;\r
-import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;\r
-import org.openecomp.sdc.toscaparser.api.parameters.Input;\r
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;\r
\r
public class CsarToscaTester {\r
public static void main(String[] args) throws Exception {\r
- ClassLoader loader = CsarToscaTester.class.getClassLoader();\r
System.out.println("CsarToscaParser - path to CSAR's Directory is " + Arrays.toString(args));\r
SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();\r
- \r
- File folder = new File(args[0].toString());\r
+\r
+ File folder = new File(args[0]);\r
File[] listOfFiles = folder.listFiles();\r
- FileWriter fw;\r
- \r
Date now = new Date();\r
SimpleDateFormat dateFormat = new SimpleDateFormat("d-MM-y-HH_mm_ss");\r
String time = dateFormat.format(now);\r
- String csarsDir = args[1].toString() + "/csar-reports-" + time;\r
+ String csarsDir = args[1] + "/csar-reports-" + time;\r
File dir = new File(csarsDir);\r
dir.mkdir();\r
- \r
- \r
+\r
+\r
for (File file : listOfFiles) {\r
if (file.isFile()) { \r
- System.out.println("File " + file.getAbsolutePath());\r
- ExceptionCollector.clear();\r
- String name = file.getName();\r
- String currentCsarDir = csarsDir+"/"+name+"-"+time;\r
+ System.out.println("File " + file.getAbsolutePath());\r
+ String name = file.getName();\r
+ String currentCsarDir = csarsDir+"/"+name+"-"+time;\r
dir = new File(currentCsarDir);\r
dir.mkdir();\r
- ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(file.getAbsolutePath());\r
- List<NodeTemplate> vflist = csarHelper.getServiceVfList();\r
- List<Input> inputs = csarHelper.getServiceInputs();\r
- List<String> exceptionReport = ExceptionCollector.getCriticalsReport();\r
- //System.out.println("CRITICALS during CSAR parsing are: " + (exceptionReport != null ? exceptionReport.toString() : "none"));\r
- List<String> warningsReport = ExceptionCollector.getWarningsReport();\r
- //System.out.println("WARNINGS during CSAR parsing are: " + (warningsReport != null ? warningsReport.toString() : "none"));\r
- \r
- \r
- \r
- if (!exceptionReport.isEmpty()) {\r
- \r
- try {\r
- fw = new FileWriter(new File(currentCsarDir + "/" + exceptionReport.size() / 2 + "-critical-" + name +"-"+time + ".txt"));\r
- for (String exception : exceptionReport) {\r
- fw.write(exception);\r
- fw.write("\r\n");\r
- }\r
- fw.close();\r
- \r
- fw = new FileWriter(new File(currentCsarDir + "/" + warningsReport.size() / 2 + "-warning-" + name +"-"+time + ".txt"));\r
- for (String warning : warningsReport) {\r
- fw.write(warning);\r
- fw.write("\r\n");\r
- }\r
- fw.close();\r
- \r
- \r
- //TODO\r
- fw = new FileWriter(new File(currentCsarDir + "/" + exceptionReport.size() / 2 + "-critical-" + name +"-"+time + ".txt"));\r
- for (String critical : exceptionReport) {\r
- fw.write(critical);\r
- fw.write("\r\n");\r
- }\r
- fw.close();\r
- \r
- } catch (IOException ex) {\r
- ex.printStackTrace();\r
- }\r
+ try {\r
+ factory.getSdcCsarHelper(file.getAbsolutePath());\r
+ } catch (SdcToscaParserException e){\r
+ System.out.println("SdcToscaParserException caught. Code: "+e.getCode()+", message: "+ e.getMessage());\r
}\r
- }\r
- \r
+ List<String> notAnalyzedReport = ThreadLocalsHolder.getCollector().getNotAnalyzedExceptionsReport();\r
+ System.out.println("NOT ANALYZED during CSAR parsing are: " + (notAnalyzedReport != null ? notAnalyzedReport.toString() : "none"));\r
+ List<String> warningsReport = ThreadLocalsHolder.getCollector().getWarningsReport();\r
+ //System.out.println("WARNINGS during CSAR parsing are: " + (warningsReport != null ? warningsReport.toString() : "none"));\r
+ List<String> criticalsReport = ThreadLocalsHolder.getCollector().getCriticalsReport();\r
+ System.out.println("CRITICALS during CSAR parsing are: " + (criticalsReport != null ? criticalsReport.toString() : "none"));\r
+\r
+ try {\r
+ generateReport(time, name, currentCsarDir, criticalsReport, "critical");\r
+ generateReport(time, name, currentCsarDir, warningsReport, "warning");\r
+ generateReport(time, name, currentCsarDir, notAnalyzedReport, "notAnalyzed");\r
+\r
+ } catch (IOException ex) {\r
+ ex.printStackTrace();\r
+ }\r
+ }\r
+\r
} \r
}\r
+\r
+ private static void generateReport(String time, String name, String currentCsarDir, List<String> criticalsReport, String type)\r
+ throws IOException {\r
+ FileWriter fw;\r
+ fw = new FileWriter(new File(currentCsarDir + "/" + criticalsReport.size() + "-"+type+"-" + name +"-"+time + ".txt"));\r
+ for (String exception : criticalsReport) {\r
+ fw.write(exception);\r
+ fw.write("\r\n");\r
+ }\r
+ fw.close();\r
+ }\r
}\r
<parent>
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-main-distribution-client</artifactId>
- <version>1.1.13-SNAPSHOT</version>
+ <version>1.1.14-SNAPSHOT</version>
</parent>
<artifactId>sdc-distribution-client</artifactId>
private static final String TLS = "TLSv1.2";
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String HTTPS = "https://";
- private static Logger log = LoggerFactory.getLogger(DistributionClientImpl.class.getName());
+ private static Logger log = LoggerFactory.getLogger(HttpAsdcClient.class.getName());
private CloseableHttpClient httpClient = null;
private String serverFqdn = null;
private String authHeaderValue = "";
<parent>\r
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>\r
<artifactId>sdc-main-distribution-client</artifactId>\r
- <version>1.1.13-SNAPSHOT</version>\r
+ <version>1.1.14-SNAPSHOT</version>\r
</parent>\r
\r
<artifactId>sdc-tosca-parser</artifactId>\r
<dependency>\r
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>\r
<artifactId>jtosca</artifactId>\r
- <version>0.1.6-SNAPSHOT</version>\r
+ <version>0.1.7-SNAPSHOT</version>\r
</dependency>\r
\r
\r
import java.io.IOException;
import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+
public class ConfigurationManager {
private static Logger log = LoggerFactory.getLogger(ConfigurationManager.class.getName());
- private static final String CONFIGURATION_FILE = "config/configuration.yaml";
+ private static final String CONFIGURATION_DIR = "config/";
private static volatile ConfigurationManager instance;
- private Configuration configuration;
+// private Configuration configuration;
+// private ErrorConfiguration errorConfiguration;
+
+ Map<String, Object> configurations = new HashMap<String, Object>();
+
+
+ private ConfigurationManager() {
+ initialConfigObjectsFromFiles();
+ }
+
+ private void initialConfigObjectsFromFiles() {
+ loadConfigurationClass(ErrorConfiguration.class);
+ loadConfigurationClass(Configuration.class);
+ }
- private ConfigurationManager() {
- URL url = Resources.getResource(CONFIGURATION_FILE);
+ private <T> void loadConfigurationClass(Class<T> clazz) {
+ T object = getObjectFromYaml(clazz);
+ configurations.put(clazz.getSimpleName(), object);
+ }
+
+
+ public <T> T getObjectFromYaml(Class<T> className) {
+
+
+ String configFileName = calculateFileName(className);
+
+ URL url = Resources.getResource(CONFIGURATION_DIR + configFileName);
String configFileContents = null;
try {
configFileContents = Resources.toString(url, Charsets.UTF_8);
log.error("ConfigurationManager - Failed to load configuration file");
}
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- this.configuration = yamlToObjectConverter.convertFromString(configFileContents, Configuration.class);
- }
+ T object = yamlToObjectConverter.convertFromString(configFileContents, className);
- public Configuration getConfiguration() {
- return configuration;
+ return object;
}
+
public static ConfigurationManager getInstance() {
if (instance == null) {
- synchronized (ConfigurationManager.class){
- if (instance == null){
+ synchronized (ConfigurationManager.class) {
+ if (instance == null) {
instance = new ConfigurationManager();
}
}
return instance;
}
- public void setConfiguration(Configuration configuration) {
- this.configuration = configuration;
+ private static <T> String calculateFileName(Class<T> className) {
+
+ String[] words = className.getSimpleName().split("(?=\\p{Upper})");
+
+ StringBuilder builder = new StringBuilder();
+
+ // There cannot be a null value returned from "split" - words != null is
+ // redundant
+ // if (words != null) {
+ boolean isFirst = true;
+ for (int i = 0; i < words.length; i++) {
+
+ String word = words[i];
+ if (word != null && !word.isEmpty()) {
+ if (!isFirst) {
+ builder.append("-");
+ } else {
+ isFirst = false;
+ }
+ builder.append(words[i].toLowerCase());
+ }
+ }
+ return builder.toString() + ".yaml";
+
+ /*
+ * } else { return className.getSimpleName().toLowerCase() + Constants.YAML_SUFFIX; }
+ */
+
+ }
+
+ public ErrorConfiguration getErrorConfiguration() {
+ return (ErrorConfiguration) configurations.get((ErrorConfiguration.class.getSimpleName()));
+ }
+
+ public Configuration getConfiguration() {
+ return (Configuration) configurations.get((Configuration.class.getSimpleName()));
}
}
--- /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.tosca.parser.config;
+
+import java.util.Map;
+
+public class ErrorConfiguration {
+
+ private Map<String, ErrorInfo> errors;
+
+ public Map<String, ErrorInfo> getErrors() {
+ return errors;
+ }
+
+ public void setErrors(Map<String, ErrorInfo> errors) {
+ this.errors = errors;
+ }
+
+ public ErrorInfo getErrorInfo(String key) {
+ ErrorInfo clone = null;
+ ErrorInfo other = errors.get(key);
+ if (other != null) {
+ clone = new ErrorInfo();
+ clone.cloneData(other);
+ }
+ return clone;
+ }
+}
--- /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.tosca.parser.config;
+
+public class ErrorInfo {
+
+ private String code;
+ private String message;
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void cloneData(ErrorInfo other) {
+ this.code = other.getCode();
+ this.message = other.getMessage();
+ }
+
+}
--- /dev/null
+package org.openecomp.sdc.tosca.parser.config;
+
+import java.util.EnumMap;
+import java.util.Map;
+
+import org.openecomp.sdc.toscaparser.api.utils.JToscaErrorCodes;
+
+public enum SdcToscaParserErrors {
+
+ BAD_FORMAT, CONFORMANCE_LEVEL_ERROR, FILE_NOT_FOUND, GENERAL_ERROR;
+
+ private static final Map<JToscaErrorCodes, SdcToscaParserErrors> JTOSCA_ERRORS =
+ new EnumMap<JToscaErrorCodes, SdcToscaParserErrors>(JToscaErrorCodes.class) {{
+
+ put(JToscaErrorCodes.GENERAL_ERROR, GENERAL_ERROR);
+
+ put(JToscaErrorCodes.PATH_NOT_VALID, FILE_NOT_FOUND);
+ //CSAR contents problems
+ put(JToscaErrorCodes.MISSING_META_FILE, BAD_FORMAT);
+ put(JToscaErrorCodes.INVALID_META_YAML_CONTENT, BAD_FORMAT);
+ put(JToscaErrorCodes.ENTRY_DEFINITION_NOT_DEFINED, BAD_FORMAT);
+ put(JToscaErrorCodes.MISSING_ENTRY_DEFINITION_FILE, BAD_FORMAT);
+ put(JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR, BAD_FORMAT);
+ put(JToscaErrorCodes.INVALID_CSAR_FORMAT, BAD_FORMAT);
+ }};
+
+ public static SdcToscaParserErrors getSdcErrorByJToscaError(JToscaErrorCodes jToscaErrorCode) {
+ return JTOSCA_ERRORS.get(jToscaErrorCode);
+ }
+
+}
package org.openecomp.sdc.tosca.parser.exceptions;\r
\r
-public class SdcToscaParserException extends Exception{\r
- /**\r
- * \r
- */\r
- private static final long serialVersionUID = 626014844866501196L;\r
- \r
- public SdcToscaParserException(String string) {\r
- super(string);\r
- }\r
+public class SdcToscaParserException extends Exception {\r
+\r
+ private static final long serialVersionUID = 626014844866501196L;\r
+ private String code;\r
+\r
+ public SdcToscaParserException(String string, String code) {\r
+ super(string);\r
+ this.code = code;\r
+ }\r
+\r
+ public String getCode() {\r
+ return code;\r
+ }\r
+\r
+ public void setCode(String code) {\r
+ this.code = code;\r
+ }\r
}\r
import java.util.*;
import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
private static final String PATH_DELIMITER = "#";
private static final String PREFIX = "port_";
- private static final String[] SUFFIX = new String[]{"_network_role_tag", "_ip_requirements", "_subnetpoolid"};
+ Pattern SUFFIX = Pattern.compile("(_network_role_tag|_ip_requirements|_subnetpoolid)$");
+// private static final String[] SUFFIX = new String[]{"_network_role_tag", "_ip_requirements", "_subnetpoolid"};
private ToscaTemplate toscaTemplate;
private static Logger log = LoggerFactory.getLogger(SdcCsarHelperImpl.class.getName());
public Map<String, Map<String, Object>> getCpPropertiesFromVfc(NodeTemplate vfc) {
+ if (vfc == null) {
+ log.error("getCpPropertiesFromVfc - vfc is null");
+ return new HashMap<>();
+ }
+
List<String> paths = new ArrayList<>();
paths.add("network_role_tag");
paths.add("ip_requirements#ip_count_required#count");
Map<String, Map<String, Object>> cps = new HashMap<>();
- for (Map.Entry<String, Property> entry : props.entrySet()) {
- String fullCpName = entry.getKey();
-
- if (fullCpName.startsWith(PREFIX) &&
- Arrays.stream(SUFFIX).parallel().anyMatch(fullCpName::endsWith))
- {
- //this is CP - get all it's properties according to paths list
- String cpName = fullCpName.replaceAll("^("+PREFIX+")", "").replaceAll("("+String.join("|", SUFFIX)+")$", "");
- cps.put(cpName, new HashMap<>());
- for (String path: paths) {
- String fullPathToSearch = PREFIX + cpName + "_" + path;
- String value = getNodeTemplatePropertyLeafValue(vfc, fullPathToSearch);
- if (value != null) {
- value = StringUtils.stripStart(value, "[");
- value = StringUtils.stripEnd(value, "]");
- cps.get(cpName).put(path, value);
+ if (props != null) {
+ for (Map.Entry<String, Property> entry : props.entrySet()) {
+ String fullCpName = entry.getKey();
+ Matcher matcher = SUFFIX.matcher(fullCpName);
+
+ if (fullCpName.startsWith(PREFIX) && matcher.find()) {
+ //this is CP - get all it's properties according to paths list
+ String cpName = fullCpName.replaceAll("^(" + PREFIX + ")", "").replaceAll(matcher.group(1), "");
+
+ List<String> propertiesToSearch = paths.stream().filter(i -> i.contains(StringUtils.stripStart(matcher.group(1), "_"))).collect(Collectors.toList());
+ for (String item : propertiesToSearch) {
+ String fullPathToSearch = PREFIX + cpName + "_" + item;
+ Object value = getNodeTemplatePropertyAsObject(vfc, fullPathToSearch);
+ if (value != null) {
+ if (!cps.containsKey(cpName))
+ cps.put(cpName, new HashMap<>());
+ }
+
+ cps.get(cpName).put(item, value);
}
}
}
Object current = property.getValue();
return iterateProcessPath(1, current, split);
}
- log.error("processProperties - property not found");
+ String propName = (split != null && split.length > 0 ? split[0] : null);
+ log.error("processProperties - property {} not found", propName);
return null;
}
}
\r
import org.openecomp.sdc.tosca.parser.api.ConformanceLevel;\r
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;\r
-import org.openecomp.sdc.tosca.parser.config.Configuration;\r
-import org.openecomp.sdc.tosca.parser.config.ConfigurationManager;\r
+import org.openecomp.sdc.tosca.parser.config.*;\r
import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;\r
import org.openecomp.sdc.tosca.parser.utils.GeneralUtility;\r
import org.openecomp.sdc.toscaparser.api.ToscaTemplate;\r
import org.openecomp.sdc.toscaparser.api.common.JToscaException;\r
+import org.openecomp.sdc.toscaparser.api.utils.JToscaErrorCodes;\r
\r
public class SdcToscaParserFactory {\r
\r
private static volatile SdcToscaParserFactory instance;\r
private static Configuration configuration;\r
+ private static ErrorConfiguration errorConfiguration;\r
\r
private SdcToscaParserFactory() {\r
\r
if (instance == null) {\r
instance = new SdcToscaParserFactory();\r
configuration = ConfigurationManager.getInstance().getConfiguration();\r
+ errorConfiguration = ConfigurationManager.getInstance().getErrorConfiguration();\r
}\r
}\r
}\r
* @param csarPath - the absolute path to CSAR file.\r
* @return ISdcCsarHelper object.\r
* @throws SdcToscaParserException - in case the path or CSAR are invalid.\r
- * @throws JToscaException - in case the path or CSAR are invalid.\r
*/\r
- public ISdcCsarHelper getSdcCsarHelper(String csarPath) throws JToscaException, SdcToscaParserException {\r
+ public ISdcCsarHelper getSdcCsarHelper(String csarPath) throws SdcToscaParserException {\r
synchronized (SdcToscaParserFactory.class) {\r
- ToscaTemplate tosca = new ToscaTemplate(csarPath, null, true, null);\r
+ ToscaTemplate tosca = null;\r
+ try {\r
+ tosca = new ToscaTemplate(csarPath, null, true, null);\r
+ } catch (JToscaException e) {\r
+ throwSdcToscaParserException(e);\r
+ }\r
SdcCsarHelperImpl sdcCsarHelperImpl = new SdcCsarHelperImpl(tosca);\r
validateCsarVersion(sdcCsarHelperImpl.getConformanceLevel());\r
return sdcCsarHelperImpl;\r
String maxVersion = level.getMaxVersion();\r
if (cSarVersion != null) {\r
if ((GeneralUtility.conformanceLevelCompare(cSarVersion, minVersion) < 0) || (GeneralUtility.conformanceLevelCompare(cSarVersion, maxVersion) > 0)) {\r
- throw new SdcToscaParserException("Model is not supported. Parser supports versions " + minVersion + " to " + maxVersion);\r
+ throwConformanceLevelException(minVersion, maxVersion);\r
}\r
} else {\r
- throw new SdcToscaParserException("Model is not supported. Parser supports versions " + minVersion + " to " + maxVersion);\r
+ throwConformanceLevelException(minVersion, maxVersion);\r
}\r
}\r
\r
+ private void throwConformanceLevelException(String minVersion, String maxVersion) throws SdcToscaParserException {\r
+ ErrorInfo errorInfo = errorConfiguration.getErrorInfo(SdcToscaParserErrors.CONFORMANCE_LEVEL_ERROR.toString());\r
+ throw new SdcToscaParserException(String.format(errorInfo.getMessage(), minVersion, maxVersion), errorInfo.getCode());\r
+ }\r
+\r
+ private void throwSdcToscaParserException(JToscaException e) throws SdcToscaParserException {\r
+ ErrorInfo errorInfo = errorConfiguration.getErrorInfo(SdcToscaParserErrors.getSdcErrorByJToscaError(JToscaErrorCodes.getByCode(e.getCode())).toString());\r
+ throw new SdcToscaParserException(errorInfo.getMessage(), errorInfo.getCode());\r
+ }\r
}
\ No newline at end of file
--- /dev/null
+# Errors
+errors:
+ FILE_NOT_FOUND: {
+ code: TP0001,
+ message: "Error: CSAR file not found."
+ }
+ BAD_FORMAT: {
+ code: TP0002,
+ message: "Error: CSAR file bad format. Check the log for details."
+ }
+ CONFORMANCE_LEVEL_ERROR: {
+ code: TP0003,
+ message: "Error: CSAR version is unsupported. Parser supports versions %s to %s."
+ }
+ GENERAL_ERROR: {
+ code: TP0004,
+ message: "Error: an unexpected internal error occured."
+ }
\ No newline at end of file
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory;
-import org.openecomp.sdc.toscaparser.api.common.ExceptionCollector;
import org.openecomp.sdc.toscaparser.api.common.JToscaException;
+import org.openecomp.sdc.toscaparser.api.utils.ThreadLocalsHolder;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
-public abstract class BasicTest {
+public abstract class SdcToscaParserBasicTest {
public static final String VF_CUSTOMIZATION_UUID = "56179cd8-de4a-4c38-919b-bbc4452d2d73";
static SdcToscaParserFactory factory;
};
};
- private static ISdcCsarHelper getCsarHelper(String path) throws JToscaException, IOException, SdcToscaParserException {
+ protected static ISdcCsarHelper getCsarHelper(String path) throws SdcToscaParserException {
System.out.println("Parsing CSAR "+path+"...");
- String fileStr1 = BasicTest.class.getClassLoader().getResource(path).getFile();
+ String fileStr1 = SdcToscaParserBasicTest.class.getClassLoader().getResource(path).getFile();
File file1 = new File(fileStr1);
ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(file1.getAbsolutePath());
- List<String> exceptionReport = ExceptionCollector.getCriticalsReport();
- if (!exceptionReport.isEmpty()){
- System.out.println("TOSCA Errors found in CSAR - failing the tests...");
- System.out.println(exceptionReport.toString());
- ExceptionCollector.clear();
- //throw new SdcToscaParserException("CSAR didn't pass validation");
- }
return sdcCsarHelper;
}
package org.openecomp.sdc.impl;
+import org.openecomp.sdc.tosca.parser.config.ErrorConfiguration;
import org.testng.annotations.Test;
import org.openecomp.sdc.tosca.parser.config.Configuration;
import org.openecomp.sdc.tosca.parser.config.ConfigurationManager;
import static org.testng.Assert.assertNotNull;
-public class ToscaParserConfigurationTest extends BasicTest {
+public class ToscaParserConfigurationTest extends SdcToscaParserBasicTest {
@Test
public void testConfigurationConformanceLevel() throws IOException {
assertNotNull(config.getConformanceLevel().getMaxVersion());
assertNotNull(config.getConformanceLevel().getMinVersion());
}
+
+
+ @Test
+ public void testErrorConfigurations() throws IOException {
+ ErrorConfiguration errorConfig = ConfigurationManager.getInstance().getErrorConfiguration();
+ assertNotNull(errorConfig);
+ assertNotNull(errorConfig.getErrors());
+ }
+
}
--- /dev/null
+package org.openecomp.sdc.impl;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+import java.io.File;
+
+import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.openecomp.sdc.toscaparser.api.utils.JToscaErrorCodes;
+
+
+/*put(JToscaErrorCodes.GENERAL_ERROR, GENERAL_ERROR);
+
+put(JToscaErrorCodes.PATH_NOT_VALID, FILE_NOT_FOUND);
+//CSAR contents problems
+put(JToscaErrorCodes.MISSING_META_FILE, BAD_FORMAT);
+put(JToscaErrorCodes.INVALID_META_YAML_CONTENT, BAD_FORMAT);
+put(JToscaErrorCodes.ENTRY_DEFINITION_NOT_DEFINED, BAD_FORMAT);
+put(JToscaErrorCodes.MISSING_ENTRY_DEFINITION_FILE, BAD_FORMAT);
+put(JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR, BAD_FORMAT);
+
+ MISSING_META_FILE("JT1001"),
+/* INVALID_META_YAML_CONTENT("JT1002"),
+/* ENTRY_DEFINITION_NOT_DEFINED("JT1003"),
+/* MISSING_ENTRY_DEFINITION_FILE("JT1004"),
+/* GENERAL_ERROR("JT1005"),
+/* PATH_NOT_VALID("JT1006"),
+/* CSAR_TOSCA_VALIDATION_ERROR("JT1007");
+
+*/
+
+/*
+ *
+ * # Errors
+errors:
+ FILE_NOT_FOUND: {
+ code: TP0001,
+ message: "Error: CSAR file not found."
+ }
+ BAD_FORMAT: {
+ code: TP0002,
+ message: "Error: CSAR file bad format. Check the log for details."
+ }
+ CONFORMANCE_LEVEL_ERROR: {
+ code: TP0003,
+ message: "Error: CSAR version is unsupported. Parser supports versions %s to %s."
+ }
+ GENERAL_ERROR: {
+ code: TP0004,
+ message: "Error: an unexpected internal error occured."
+ }
+ *
+ */
+
+public class ToscaParserErrorHandlingTest extends SdcToscaParserBasicTest {
+
+
+ @Test
+ public void testMissingMetadata(){
+ String csarPath = "csars/service-missing-meta-file.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+
+ @Test
+ public void testInvalidYamlContentMeta(){
+ String csarPath = "csars/service-invalid-yaml-content-meta.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+ @Test
+ public void testEntryDefinitionNotDefined(){
+ String csarPath = "csars/service-entry-definition-not-defined.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+ @Test
+ public void testMissingEntryDefinitionFile(){
+ String csarPath = "csars/service-missing-entry-definition.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+ //@Test - PA - there are currently no critical erros in JTosca
+ public void tesValidationError(){
+ String csarPath = "csars/service-invalid-input-args.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+ @Test
+ public void testInValidConformanceLevelError(){
+ String csarPath = "csars/service-invalid-conformence-level.csar";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0003");
+ }
+
+ @Test
+ public void testFileNotFound(){
+ Throwable captureThrowable = captureThrowable("csars/XXX.csar");
+ testThrowable(captureThrowable, "TP0001");
+ }
+
+ @Test
+ public void testInvalidCsarFormat(){
+ String csarPath = "csars/csar-invalid-zip.zip";
+ String fileLocationString = ToscaParserErrorHandlingTest.class.getClassLoader().getResource(csarPath).getFile();
+ File file = new File(fileLocationString);
+ Throwable captureThrowable = captureThrowable(file.getAbsolutePath());
+ testThrowable(captureThrowable, "TP0002");
+ }
+
+ private static void testThrowable(Throwable captureThrowable, String expectedCode) {
+ assertNotNull(captureThrowable);
+ assertTrue(captureThrowable instanceof SdcToscaParserException, "Error thrown is of type "+captureThrowable.getClass().getSimpleName());
+ assertEquals(((SdcToscaParserException)captureThrowable).getCode(), expectedCode);
+ }
+
+ public static Throwable captureThrowable(String csarPath) {
+ Throwable result = null;
+ try {
+ factory.getSdcCsarHelper(csarPath);
+ } catch( Throwable throwable ) {
+ result = throwable;
+ }
+ return result;
+ }
+}
import static org.testng.Assert.assertTrue;
-public class ToscaParserGeneralUtilTest extends BasicTest {
+public class ToscaParserGeneralUtilTest extends SdcToscaParserBasicTest {
@Test
public void testVersionCompare() {
import static org.testng.Assert.*;
-public class ToscaParserGroupTest extends BasicTest{
+public class ToscaParserGroupTest extends SdcToscaParserBasicTest{
//region getVfModulesByVf
@Test
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
-public class ToscaParserMetadataTest extends BasicTest {
+public class ToscaParserMetadataTest extends SdcToscaParserBasicTest {
//region getServiceMetadata
@Test
import org.openecomp.sdc.toscaparser.api.Group;
import org.openecomp.sdc.toscaparser.api.NodeTemplate;
-public class ToscaParserNodeTemplateTest extends BasicTest {
+public class ToscaParserNodeTemplateTest extends SdcToscaParserBasicTest {
//region getServiceVfList
@Test
List<NodeTemplate> vfcs = complexCps.getVfcListByVf(VF_CUSTOMIZATION_UUID);
Map<String, Map<String, Object>> cps = complexCps.getCpPropertiesFromVfc(vfcs.get(0));
- assertEquals("1", cps.get("port_fe1_sigtran").get("ip_requirements#ip_count_required#count"));
- assertEquals("true", cps.get("port_fe1_sigtran").get("ip_requirements#dhcp_enabled"));
- assertEquals("4", cps.get("port_fe1_sigtran").get("ip_requirements#ip_version"));
+ assertEquals(5, cps.size());
- assertEquals("2", cps.get("port_fe_cluster").get("ip_requirements#ip_count_required#count"));
- assertEquals("true", cps.get("port_fe_cluster").get("ip_requirements#dhcp_enabled"));
- assertEquals("4", cps.get("port_fe_cluster").get("ip_requirements#ip_version"));
+ assertEquals(1, cps.get("port_fe1_sigtran").get("ip_requirements#ip_count_required#count"));
+ assertEquals(true, cps.get("port_fe1_sigtran").get("ip_requirements#dhcp_enabled"));
+ assertEquals(4, cps.get("port_fe1_sigtran").get("ip_requirements#ip_version"));
+
+ assertEquals(2, cps.get("port_fe_cluster").get("ip_requirements#ip_count_required#count"));
+ assertEquals(true, cps.get("port_fe_cluster").get("ip_requirements#dhcp_enabled"));
+ assertEquals(4, cps.get("port_fe_cluster").get("ip_requirements#ip_version"));
+ }
+
+ @Test
+ public void testGetCpPropertiesFromVfcForNullVFC() {
+ Map<String, Map<String, Object>> cps = complexCps.getCpPropertiesFromVfc(null);
+ assertNotNull(cps);
+ assertEquals(0, cps.size());
}
//endregion
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
-public class ToscaParserServiceInputTest extends BasicTest {
+public class ToscaParserServiceInputTest extends SdcToscaParserBasicTest {
//region getServiceInputs
@Test
//import static org.junit.Assert.assertEquals;
//import static org.junit.Assert.assertNull;
-public class ToscaParserSubsMappingsTest extends BasicTest {
+public class ToscaParserSubsMappingsTest extends SdcToscaParserBasicTest {
//region getServiceSubstitutionMappingsTypeName
@Test
--- /dev/null
+# Errors
+errors:
+ FILE_NOT_FOUND: {
+ code: TP0001,
+ message: "Error: CSAR file not found."
+ }
+ BAD_FORMAT: {
+ code: TP0002,
+ message: "Error: CSAR file bad format. Check the log for details."
+ }
+ CONFORMANCE_LEVEL_ERROR: {
+ code: TP0003,
+ message: "Error: CSAR version is unsupported. Parser supports versions %s to %s."
+ }
+ GENERAL_ERROR: {
+ code: TP0004,
+ message: "Error: an unexpected internal error occured."
+ }
\ No newline at end of file
--- /dev/null
+SDC-TOSCA-Meta-File-Version: 1.0
+SDC-TOSCA-Definitions-Version: 2.0