aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sdc/tosca/parser/impl/SdcToscaParserFactory.java
blob: c9cac1c9b7173d435e2397c901df9a36b705aed8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package org.openecomp.sdc.tosca.parser.impl;

import java.util.ArrayList;
import java.util.List;

import org.openecomp.sdc.tosca.parser.api.ConformanceLevel;
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
import org.openecomp.sdc.tosca.parser.config.*;
import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
import org.openecomp.sdc.tosca.parser.utils.GeneralUtility;
import org.openecomp.sdc.toscaparser.api.ToscaTemplate;
import org.openecomp.sdc.toscaparser.api.common.JToscaValidationIssue;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SdcToscaParserFactory {
	private static Logger log = LoggerFactory.getLogger(SdcToscaParserFactory.class.getName());
	
    private static volatile SdcToscaParserFactory instance;
    private static Configuration configuration;
    private static ErrorConfiguration errorConfiguration;
    private static JtoscaValidationIssueConfiguration jtoscaValidationIssueConfiguration;
    private List<JToscaValidationIssue> criticalExceptions = new ArrayList<>();
    private List<JToscaValidationIssue> warningExceptions = new ArrayList<>();
    private List<JToscaValidationIssue> notAnalyzadExceptions = new ArrayList<>();
    private SdcToscaParserFactory() {

    }

    /**
     * Get an SdcToscaParserFactory instance.
     * @return SdcToscaParserFactory instance.
     */
    public static SdcToscaParserFactory getInstance() {
        if (instance == null) {
            synchronized (SdcToscaParserFactory.class) {
                if (instance == null) {
                    instance = new SdcToscaParserFactory();
                    configuration = ConfigurationManager.getInstance().getConfiguration();
                    errorConfiguration = ConfigurationManager.getInstance().getErrorConfiguration();
                    jtoscaValidationIssueConfiguration = ConfigurationManager.getInstance().getJtoscaValidationIssueConfiguration();
                }
            }
        }
        return instance;
    }

    /**
     * Get an ISdcCsarHelper object for this CSAR file.
     *
     * @param csarPath - the absolute path to CSAR file.
     * @return ISdcCsarHelper object.
     * @throws SdcToscaParserException - in case the path or CSAR are invalid.
     */
    public ISdcCsarHelper getSdcCsarHelper(String csarPath) throws SdcToscaParserException {
        return init(csarPath, true);
    }

    /**
     * Get an ISdcCsarHelper object for this CSAR file.
     *
     * @param csarPath - the absolute path to CSAR file.
     * @param resolveGetInput - resolve get_input properties
     * @return ISdcCsarHelper object.
     * @throws SdcToscaParserException - in case the path or CSAR are invalid.
     */
    public ISdcCsarHelper getSdcCsarHelper(String csarPath, boolean resolveGetInput) throws SdcToscaParserException {
        return init(csarPath, resolveGetInput);
    }

    private ISdcCsarHelper init(String csarPath, boolean resolveGetInput) throws SdcToscaParserException {
        synchronized (SdcToscaParserFactory.class) {
            ToscaTemplate tosca = null;
            try {
                tosca = new ToscaTemplate(csarPath, null, true, null, resolveGetInput);
            } catch (JToscaException e) {
                throwSdcToscaParserException(e);
            }
            SdcCsarHelperImpl sdcCsarHelperImpl = new SdcCsarHelperImpl(tosca);
            String cSarConformanceLevel = sdcCsarHelperImpl.getConformanceLevel();
            validateCsarVersion(cSarConformanceLevel);
            try {
                handleErrorsByTypes(csarPath, cSarConformanceLevel);
			} catch (JToscaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return sdcCsarHelperImpl;
        }
    }

    private void handleErrorsByTypes(String csarPath, String cSarConformanceLevel) throws JToscaException {
        clearValidationIssuesLists();
    	for(JToscaValidationIssue toscaValidationIssue : ThreadLocalsHolder.getCollector().getValidationIssues().values()){
            List<JToscaValidationIssueInfo> issueInfos = jtoscaValidationIssueConfiguration.getValidationIssues().get(toscaValidationIssue.getCode());
    		if(issueInfos != null && !issueInfos.isEmpty()){
                JToscaValidationIssueInfo issueInfo = null;
    			issueInfo = issueInfos.stream()
                    .filter(i-> isMatchConformanceLevel(cSarConformanceLevel,i.getSinceCsarConformanceLevel()))
                    .max((i1,i2) -> GeneralUtility.conformanceLevelCompare(i1.getSinceCsarConformanceLevel(), i2.getSinceCsarConformanceLevel()) )
                    .orElse(null);

    			if(issueInfo != null){
                    switch (JToscaValidationIssueType.valueOf(issueInfo.getIssueType())) {
                        case CRITICAL:
                            criticalExceptions.add(toscaValidationIssue);
                            break;
                        case WARNING:
                            warningExceptions.add(toscaValidationIssue);
                            break;
                        default:
                            break;
                    }
                }else{
                    notAnalyzadExceptions.add(toscaValidationIssue);
                }
            }else{//notAnalyzed
                notAnalyzadExceptions.add(toscaValidationIssue);
            }
    	}
    	logErrors(csarPath);
    }

    private void clearValidationIssuesLists(){
        notAnalyzadExceptions.clear();
        criticalExceptions.clear();
        warningExceptions.clear();
    }

    private void logErrors(String inputPath) throws JToscaException{
		//Warnings
		int warningsCount = warningExceptions.size();
		if (warningsCount > 0) {
			log.warn("####################################################################################################");
			log.warn("CSAR Warnings found! CSAR name - {}", inputPath);
			log.warn("ToscaTemplate - verifyTemplate - {} Parsing Warning{} occurred...", warningsCount, (warningsCount > 1 ? "s" : ""));
			for (JToscaValidationIssue info : warningExceptions) {
				log.warn("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath);
			}
			log.warn("####################################################################################################");
		}
		//Criticals
		int criticalsCount = criticalExceptions.size();
		if (criticalsCount > 0) {
			log.error("####################################################################################################");
			log.error("ToscaTemplate - verifyTemplate - {} Parsing Critical{} occurred...", criticalsCount, (criticalsCount > 1 ? "s" : ""));
			for (JToscaValidationIssue info : criticalExceptions) {
				log.error("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath);
			}
			throw new JToscaException(String.format("CSAR Validation Failed. CSAR name - {}. Please check logs for details.", inputPath), JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR.getValue());
		}
    }
    public List<JToscaValidationIssue> getCriticalExceptions() {
		return criticalExceptions;
	}

	public List<JToscaValidationIssue> getWarningExceptions() {
		return warningExceptions;
	}

	public List<JToscaValidationIssue> getNotAnalyzadExceptions() {
		return notAnalyzadExceptions;
	}


	private void validateCsarVersion(String cSarVersion) throws SdcToscaParserException {
        ConformanceLevel level = configuration.getConformanceLevel();
        String minVersion = level.getMinVersion();
        String maxVersion = level.getMaxVersion();
        if (cSarVersion != null) {
            if ((GeneralUtility.conformanceLevelCompare(cSarVersion, minVersion) < 0) || (GeneralUtility.conformanceLevelCompare(cSarVersion, maxVersion) > 0)) {
                throwConformanceLevelException(minVersion, maxVersion);
            }
        } else {
            throwConformanceLevelException(minVersion, maxVersion);
        }
    }

    private boolean isMatchConformanceLevel(String ValidationIssueVersion, String cSarVersion){
        if (ValidationIssueVersion != null && cSarVersion != null) {
            if ((GeneralUtility.conformanceLevelCompare(ValidationIssueVersion, cSarVersion) >= 0)) {
                return true;
            }
        }
        return false;
    }
    private void throwConformanceLevelException(String minVersion, String maxVersion) throws SdcToscaParserException {
        ErrorInfo errorInfo = errorConfiguration.getErrorInfo(SdcToscaParserErrors.CONFORMANCE_LEVEL_ERROR.toString());
        throw new SdcToscaParserException(String.format(errorInfo.getMessage(), minVersion, maxVersion), errorInfo.getCode());
    }

    private void throwSdcToscaParserException(JToscaException e) throws SdcToscaParserException {
        ErrorInfo errorInfo = errorConfiguration.getErrorInfo(SdcToscaParserErrors.getSdcErrorByJToscaError(JToscaErrorCodes.getByCode(e.getCode())).toString());
        throw new SdcToscaParserException(errorInfo.getMessage(), errorInfo.getCode());
    }

}