Move jTosca contents to sdc-tosca
[sdc/sdc-tosca.git] / sdc-tosca / src / main / java / org / onap / sdc / tosca / parser / impl / SdcToscaParserFactory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * sdc-tosca
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.sdc.tosca.parser.impl;
22
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.onap.sdc.tosca.parser.api.ConformanceLevel;
27 import org.onap.sdc.tosca.parser.config.ConfigurationManager;
28 import org.onap.sdc.tosca.parser.config.ErrorInfo;
29 import org.onap.sdc.tosca.parser.config.JToscaValidationIssueInfo;
30 import org.onap.sdc.tosca.parser.config.SdcToscaParserErrors;
31 import org.onap.sdc.tosca.parser.enums.JToscaValidationIssueType;
32 import org.onap.sdc.tosca.parser.utils.GeneralUtility;
33 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
34 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
35 import org.onap.sdc.toscaparser.api.ToscaTemplate;
36 import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue;
37 import org.onap.sdc.toscaparser.api.common.JToscaException;
38 import org.onap.sdc.toscaparser.api.utils.JToscaErrorCodes;
39 import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class SdcToscaParserFactory {
44         private static Logger log = LoggerFactory.getLogger(SdcToscaParserFactory.class.getName());
45
46     private static ConfigurationManager configurationManager;
47     private static volatile SdcToscaParserFactory instance;
48     private List<JToscaValidationIssue> criticalExceptions = new ArrayList<>();
49     private List<JToscaValidationIssue> warningExceptions = new ArrayList<>();
50     private List<JToscaValidationIssue> notAnalyzadExceptions = new ArrayList<>();
51     private SdcToscaParserFactory() {}
52
53     /**
54      * Get an SdcToscaParserFactory instance.
55      * @return SdcToscaParserFactory instance.
56      */
57     public static SdcToscaParserFactory getInstance() {
58         if (instance == null) {
59             synchronized (SdcToscaParserFactory.class) {
60                 if (instance == null) {
61                     instance = new SdcToscaParserFactory();
62                     configurationManager = ConfigurationManager.getInstance();
63                 }
64             }
65         }
66         return instance;
67     }
68
69     public static void setConfigurationManager(ConfigurationManager configurationManager) {
70         SdcToscaParserFactory.configurationManager = configurationManager;
71     }
72
73     /**
74      * Get an ISdcCsarHelper object for this CSAR file.
75      *
76      * @param csarPath - the absolute path to CSAR file.
77      * @return ISdcCsarHelper object.
78      * @throws SdcToscaParserException - in case the path or CSAR are invalid.
79      */
80     public ISdcCsarHelper getSdcCsarHelper(String csarPath) throws SdcToscaParserException {
81         return init(csarPath, true);
82     }
83
84     /**
85      * Get an ISdcCsarHelper object for this CSAR file.
86      *
87      * @param csarPath - the absolute path to CSAR file.
88      * @param resolveGetInput - resolve get_input properties
89      * @return ISdcCsarHelper object.
90      * @throws SdcToscaParserException - in case the path or CSAR are invalid.
91      */
92     public ISdcCsarHelper getSdcCsarHelper(String csarPath, boolean resolveGetInput) throws SdcToscaParserException {
93         return init(csarPath, resolveGetInput);
94     }
95
96     private ISdcCsarHelper init(String csarPath, boolean resolveGetInput) throws SdcToscaParserException {
97         synchronized (SdcToscaParserFactory.class) {
98             ToscaTemplate tosca = null;
99             try {
100                 tosca = new ToscaTemplate(csarPath, null, true, null, resolveGetInput);
101             } catch (JToscaException e) {
102                 throwSdcToscaParserException(e);
103             }
104             SdcCsarHelperImpl sdcCsarHelperImpl = new SdcCsarHelperImpl(tosca, configurationManager);
105             String cSarConformanceLevel = sdcCsarHelperImpl.getConformanceLevel();
106             validateCsarVersion(cSarConformanceLevel);
107             try {
108                 handleErrorsByTypes(csarPath, cSarConformanceLevel);
109                         } catch (JToscaException e) {
110                 throwSdcToscaParserException(e);
111                         }
112             return sdcCsarHelperImpl;
113         }
114     }
115
116     private void handleErrorsByTypes(String csarPath, String cSarConformanceLevel) throws JToscaException {
117         clearValidationIssuesLists();
118         for(JToscaValidationIssue toscaValidationIssue : ThreadLocalsHolder.getCollector().getValidationIssues().values()){
119             List<JToscaValidationIssueInfo> issueInfos = configurationManager.getJtoscaValidationIssueConfiguration().getValidationIssues().get(toscaValidationIssue.getCode());
120                 if(issueInfos != null && !issueInfos.isEmpty()){
121                 JToscaValidationIssueInfo issueInfo = null;
122                         issueInfo = issueInfos.stream()
123                     .filter(i-> isMatchConformanceLevel(cSarConformanceLevel,i.getSinceCsarConformanceLevel()))
124                     .max((i1,i2) -> GeneralUtility.conformanceLevelCompare(i1.getSinceCsarConformanceLevel(), i2.getSinceCsarConformanceLevel()) )
125                     .orElse(null);
126
127                         if(issueInfo != null){
128                     switch (JToscaValidationIssueType.valueOf(issueInfo.getIssueType())) {
129                         case CRITICAL:
130                             criticalExceptions.add(toscaValidationIssue);
131                             break;
132                         case WARNING:
133                             warningExceptions.add(toscaValidationIssue);
134                             break;
135                         default:
136                             break;
137                     }
138                 }else{
139                     notAnalyzadExceptions.add(toscaValidationIssue);
140                 }
141             }else{//notAnalyzed
142                 notAnalyzadExceptions.add(toscaValidationIssue);
143             }
144         }
145         logErrors(csarPath);
146     }
147
148     private void clearValidationIssuesLists(){
149         notAnalyzadExceptions.clear();
150         criticalExceptions.clear();
151         warningExceptions.clear();
152     }
153
154     private void logErrors(String inputPath) throws JToscaException{
155                 //Warnings
156                 int warningsCount = warningExceptions.size();
157                 if (warningsCount > 0) {
158                         log.warn("####################################################################################################");
159                         log.warn("CSAR Warnings found! CSAR name - {}", inputPath);
160                         log.warn("ToscaTemplate - verifyTemplate - {} Parsing Warning{} occurred...", warningsCount, (warningsCount > 1 ? "s" : ""));
161                         for (JToscaValidationIssue info : warningExceptions) {
162                                 log.warn("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath);
163                         }
164                         log.warn("####################################################################################################");
165                 }
166                 //Criticals
167                 int criticalsCount = criticalExceptions.size();
168                 if (criticalsCount > 0) {
169                         log.error("####################################################################################################");
170                         log.error("ToscaTemplate - verifyTemplate - {} Parsing Critical{} occurred...", criticalsCount, (criticalsCount > 1 ? "s" : ""));
171                         for (JToscaValidationIssue info : criticalExceptions) {
172                                 log.error("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath);
173                         }
174                         throw new JToscaException(String.format("CSAR Validation Failed. CSAR name - {}. Please check logs for details.", inputPath), JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR.getValue());
175                 }
176     }
177     public List<JToscaValidationIssue> getCriticalExceptions() {
178                 return criticalExceptions;
179         }
180
181         public List<JToscaValidationIssue> getWarningExceptions() {
182                 return warningExceptions;
183         }
184
185         public List<JToscaValidationIssue> getNotAnalyzadExceptions() {
186                 return notAnalyzadExceptions;
187         }
188
189
190         private void validateCsarVersion(String cSarVersion) throws SdcToscaParserException {
191         ConformanceLevel level = configurationManager.getConfiguration().getConformanceLevel();
192         String minVersion = level.getMinVersion();
193         if (cSarVersion != null) {
194             if (GeneralUtility.conformanceLevelCompare(cSarVersion, minVersion) < 0) {
195                 throwConformanceLevelException(minVersion);
196             }
197         } else {
198             throwConformanceLevelException(minVersion);
199         }
200     }
201
202     private boolean isMatchConformanceLevel(String ValidationIssueVersion, String cSarVersion){
203         if (ValidationIssueVersion != null && cSarVersion != null) {
204             if ((GeneralUtility.conformanceLevelCompare(ValidationIssueVersion, cSarVersion) >= 0)) {
205                 return true;
206             }
207         }
208         return false;
209     }
210     private void throwConformanceLevelException(String minVersion) throws SdcToscaParserException {
211         ErrorInfo errorInfo = configurationManager.getErrorConfiguration().getErrorInfo(SdcToscaParserErrors.CONFORMANCE_LEVEL_ERROR.toString());
212         throw new SdcToscaParserException(String.format(errorInfo.getMessage(), minVersion), errorInfo.getCode());
213     }
214
215     private void throwSdcToscaParserException(JToscaException e) throws SdcToscaParserException {
216         ErrorInfo errorInfo = configurationManager.getErrorConfiguration().getErrorInfo(SdcToscaParserErrors.getSdcErrorByJToscaError(JToscaErrorCodes.getByCode(e.getCode())).toString());
217         throw new SdcToscaParserException(errorInfo.getMessage(), errorInfo.getCode());
218     }
219
220
221
222 }