1c2c408c1adfe56ed87a7d52638868b848d5cd6f
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.tosca.services.impl;
18
19 import org.apache.commons.io.FilenameUtils;
20 import org.openecomp.core.utilities.file.FileContentHandler;
21 import org.openecomp.core.utilities.file.FileUtils;
22 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
23 import org.openecomp.core.validation.ErrorMessageCode;
24 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
25 import org.openecomp.sdc.datatypes.error.ErrorLevel;
26 import org.openecomp.sdc.datatypes.error.ErrorMessage;
27 import org.openecomp.sdc.logging.api.Logger;
28 import org.openecomp.sdc.logging.api.LoggerFactory;
29 import org.openecomp.sdc.tosca.parser.config.ConfigurationManager;
30 import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
31 import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory;
32 import org.openecomp.sdc.tosca.services.ToscaValidationService;
33 import org.openecomp.sdc.toscaparser.api.common.JToscaValidationIssue;
34 import org.yaml.snakeyaml.Yaml;
35
36 import java.io.BufferedInputStream;
37 import java.io.File;
38 import java.io.FileInputStream;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.util.HashMap;
44 import java.util.LinkedHashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.stream.Collectors;
48
49 public class ToscaValidationServiceImpl implements ToscaValidationService {
50
51   private static final Logger LOGGER = LoggerFactory.getLogger(ToscaValidationServiceImpl.class);
52   private static final String SDCPARSER_JTOSCA_VALIDATIONISSUE_CONFIG =
53       "SDCParser_jtosca-validation-issue-configuration.yaml";
54   private static final String SDCPARSER_ERROR_CONFIG = "SDCParser_error-configuration.yaml";
55   private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version";
56
57   static {
58     // Override default SDC Parser configuration
59     ConfigurationManager configurationManager = ConfigurationManager.getInstance();
60     configurationManager.setJtoscaValidationIssueConfiguration(SDCPARSER_JTOSCA_VALIDATIONISSUE_CONFIG);
61     configurationManager.setErrorConfiguration(SDCPARSER_ERROR_CONFIG);
62     SdcToscaParserFactory.setConfigurationManager(configurationManager);
63   }
64
65   @Override
66   public Map<String, List<ErrorMessage>> validate(FileContentHandler fileContentHandler)
67       throws IOException {
68
69     Path dir =
70         Files.createTempDirectory(OnboardingTypesEnum.CSAR + "_" + System.currentTimeMillis());
71     try {
72       // Write temporary files and folders to File System
73       Map<String, String> filePaths = FileUtils.writeFilesFromFileContentHandler
74           (fileContentHandler, dir);
75       // Process Tosca Yaml validation
76       return processToscaYamls(filePaths);
77     } finally {
78       // Cleanup temporary files and folders from file system
79       org.apache.commons.io.FileUtils.deleteDirectory(dir.toFile());
80     }
81   }
82
83   private Map<String, List<ErrorMessage>> processToscaYamls(Map<String, String> filePaths) {
84     Map<String, String> validFilePaths = getValidFilePaths(filePaths);
85     Map<String, List<ErrorMessage>> validationIssues = new HashMap<>();
86
87     // Process Yaml Files
88     for (Map.Entry<String, String> fileEntry : validFilePaths.entrySet()) {
89       try {
90         SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
91         factory.getSdcCsarHelper(fileEntry.getValue());
92         processValidationIssues(fileEntry.getKey(), factory, validationIssues);
93       } catch (SdcToscaParserException stpe) {
94         LOGGER.error("SDC Parser Exception from SDC Parser Library : " + stpe);
95         ErrorMessage.ErrorMessageUtil.addMessage(fileEntry.getKey(), validationIssues).add(
96             new ErrorMessage(ErrorLevel.ERROR, ErrorMessagesFormatBuilder
97                 .getErrorWithParameters(new ErrorMessageCode("JE000"), "Unexpected Error "
98                     + "occurred")));
99       }
100       catch (RuntimeException rte) {
101         LOGGER.error("Runtime Exception from SDC Parser Library : " + rte);
102         ErrorMessage.ErrorMessageUtil.addMessage(fileEntry.getKey(), validationIssues).add(
103             new ErrorMessage(ErrorLevel.ERROR, ErrorMessagesFormatBuilder
104                 .getErrorWithParameters(new ErrorMessageCode("JE000"), "Unexpected Error "
105                     + "occurred")));
106       }
107     }
108     return validationIssues;
109   }
110
111   private Map<String, String> getValidFilePaths(Map<String, String> filePaths) {
112     return filePaths.entrySet()
113         .stream()
114         .filter(map -> FileUtils.isValidYamlExtension(FilenameUtils.getExtension(map.getKey()))
115             && isToscaYaml(map.getValue()))
116         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
117   }
118
119   private boolean isToscaYaml(String filePath) {
120    boolean retValue = false;
121
122     try (InputStream input = new BufferedInputStream(new FileInputStream(new File(filePath)));) {
123       Yaml yaml = new Yaml();
124       LinkedHashMap<String,Object> data = (LinkedHashMap) yaml.load(input);
125       if(data.get(TOSCA_DEFINITION_VERSION) != null) {
126         retValue = true;
127       }
128     }
129     catch(Exception e){
130       LOGGER.info("Ignore the exception as the input file may not be a Tosca Yaml; let the " +
131           "default value return", e);
132     }
133     return retValue;
134   }
135
136   private void processValidationIssues(String fileName, SdcToscaParserFactory factory, Map<String,
137       List<ErrorMessage>> validationIssues) {
138
139     List<JToscaValidationIssue> criticalsReport = factory.getCriticalExceptions();
140     criticalsReport.stream().forEach(err ->
141         ErrorMessage.ErrorMessageUtil.addMessage(fileName, validationIssues).add(
142             new ErrorMessage(ErrorLevel.ERROR, ErrorMessagesFormatBuilder
143                 .getErrorWithParameters(new ErrorMessageCode(err.getCode()), err.getMessage()))));
144
145     List<JToscaValidationIssue> warningsReport = factory.getWarningExceptions();
146     warningsReport.stream().forEach(err ->
147         ErrorMessage.ErrorMessageUtil.addMessage(fileName, validationIssues).add(
148             new ErrorMessage(ErrorLevel.WARNING, ErrorMessagesFormatBuilder
149                 .getErrorWithParameters(new ErrorMessageCode(err.getCode()), err.getMessage()))));
150
151     List<JToscaValidationIssue> notAnalyzedReport = factory.getNotAnalyzadExceptions();
152     notAnalyzedReport.stream().forEach(err ->
153         ErrorMessage.ErrorMessageUtil.addMessage(fileName, validationIssues).add(
154             new ErrorMessage(ErrorLevel.WARNING, ErrorMessagesFormatBuilder
155                 .getErrorWithParameters(new ErrorMessageCode(err.getCode()), err.getMessage()))));
156
157   }
158
159 }