2 * Copyright © 2016-2017 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.validation.impl.validators;
19 import org.onap.sdc.tosca.services.YamlUtil;
20 import org.openecomp.core.validation.ErrorMessageCode;
21 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
22 import org.openecomp.core.validation.types.GlobalValidationContext;
23 import org.openecomp.sdc.common.errors.Messages;
24 import org.openecomp.sdc.datatypes.error.ErrorLevel;
25 import org.openecomp.sdc.validation.Validator;
26 import org.openecomp.sdc.validation.impl.util.YamlValidatorUtil;
28 import java.io.InputStream;
29 import java.util.Collection;
31 import java.util.Optional;
33 public class YamlValidator implements Validator {
34 private static final ErrorMessageCode ERROR_CODE_YML_1 = new ErrorMessageCode("YML1");
35 private static final ErrorMessageCode ERROR_CODE_YML_2 = new ErrorMessageCode("YML2");
38 public void validate(GlobalValidationContext globalContext) {
39 Collection<String> files = globalContext.files(
40 (fileName, globalValidationContext) -> fileName.endsWith(".yaml")
41 || fileName.endsWith(".yml") || fileName.endsWith(".env"));
43 files.stream().forEach(fileName -> validate(fileName, globalContext));
46 private void validate(String fileName, GlobalValidationContext globalContext) {
47 Optional<InputStream> rowContent = globalContext.getFileContent(fileName);
48 if (!rowContent.isPresent()) {
49 globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
50 .getErrorWithParameters(ERROR_CODE_YML_1, Messages
51 .INVALID_YAML_FORMAT_REASON.getErrorMessage(),
52 Messages.EMPTY_YAML_FILE.getErrorMessage()));
53 return; /* no need to continue validation */
57 convert(rowContent.get(), Map.class);
58 } catch (Exception exception) {
60 globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
61 .getErrorWithParameters(ERROR_CODE_YML_2, Messages
62 .INVALID_YAML_FORMAT_REASON.getErrorMessage(),
63 YamlValidatorUtil.getParserExceptionReason(exception)));
67 private <T> T convert(InputStream content, Class<T> type) {
68 return new YamlUtil().yamlToObject(content, type);