59dea8afb9d512e9b774667d64e5d82bbb3c267c
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation;
22
23 import org.apache.commons.collections4.MapUtils;
24 import org.junit.Assert;
25 import org.openecomp.core.translator.api.HeatToToscaTranslator;
26 import org.openecomp.core.translator.datatypes.TranslatorOutput;
27 import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
28 import org.openecomp.core.utilities.file.FileUtils;
29 import org.openecomp.core.validation.util.MessageContainerUtil;
30 import org.openecomp.sdc.common.errors.CoreException;
31 import org.openecomp.sdc.common.errors.ErrorCategory;
32 import org.openecomp.sdc.common.errors.ErrorCode;
33 import org.openecomp.sdc.datatypes.error.ErrorLevel;
34 import org.openecomp.sdc.datatypes.error.ErrorMessage;
35 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
36 import org.openecomp.sdc.logging.types.LoggerConstants;
37 import org.openecomp.sdc.logging.types.LoggerErrorCode;
38 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
39 import org.openecomp.sdc.tosca.services.ToscaFileOutputService;
40 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
41 import org.openecomp.sdc.translator.TestUtils;
42
43 import java.io.BufferedInputStream;
44 import java.io.File;
45 import java.io.FileInputStream;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.net.URL;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.zip.ZipEntry;
55 import java.util.zip.ZipInputStream;
56
57 import static org.junit.Assert.assertEquals;
58
59
60 public class BaseFullTranslationTest {
61
62   public static final String IN_POSTFIX = "/in";
63   public static final String OUT_POSTFIX = "/out";
64
65   protected void testTranslationWithInit(String path) throws IOException {
66     File translatedZipFile = initTranslatorAndTranslate(path);
67     testTranslation(path, translatedZipFile);
68   }
69
70   protected File initTranslatorAndTranslate(String path) throws IOException {
71     HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
72     return translateZipFile(path, heatToToscaTranslator);
73   }
74
75   protected void testTranslation(String basePath, File translatedZipFile) throws IOException {
76
77     URL url = BaseFullTranslationTest.class.getResource(basePath + OUT_POSTFIX);
78     Set<String> expectedResultFileNameSet = new HashSet<>();
79     Map<String, byte[]> expectedResultMap = new HashMap<>();
80
81     String path = url.getPath();
82     File pathFile = new File(path);
83     File[] files = pathFile.listFiles();
84     Assert.assertNotNull("manifest files is empty", files);
85     for (File expectedFile : files) {
86       expectedResultFileNameSet.add(expectedFile.getName());
87       try (FileInputStream input = new FileInputStream(expectedFile)) {
88         expectedResultMap.put(expectedFile.getName(), FileUtils.toByteArray(input));
89       }
90     }
91
92     try (FileInputStream fis = new FileInputStream(translatedZipFile);
93          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
94       ZipEntry entry;
95       String name;
96       String expected;
97       String actual;
98
99       while ((entry = zis.getNextEntry()) != null) {
100
101         name = entry.getName()
102             .substring(entry.getName().lastIndexOf(File.separator) + 1, entry.getName().length());
103         if (expectedResultFileNameSet.contains(name)) {
104           expected = new String(expectedResultMap.get(name)).trim().replace("\r", "");
105           actual = new String(FileUtils.toByteArray(zis)).trim().replace("\r", "");
106           assertEquals("difference in file: " + name, expected, actual);
107
108           expectedResultFileNameSet.remove(name);
109         }
110       }
111       if (expectedResultFileNameSet.isEmpty()) {
112         expectedResultFileNameSet.forEach(System.out::println);
113       }
114     }
115     assertEquals(0, expectedResultFileNameSet.size());
116   }
117
118   private File translateZipFile(String basePath, HeatToToscaTranslator heatToToscaTranslator) throws IOException {
119     URL inputFilesUrl = this.getClass().getResource(basePath + IN_POSTFIX);
120     String path = inputFilesUrl.getPath();
121     TestUtils.addFilesToTranslator(heatToToscaTranslator, path);
122     TranslatorOutput translatorOutput = heatToToscaTranslator.translate();
123     Assert.assertNotNull(translatorOutput);
124     if (MapUtils.isNotEmpty(translatorOutput.getErrorMessages()) && MapUtils.isNotEmpty(
125         MessageContainerUtil
126             .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()))) {
127       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
128           LoggerTragetServiceName.VALIDATE_HEAT_BEFORE_TRANSLATE, ErrorLevel.ERROR.name(),
129           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't translate HEAT file");
130       throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
131           "Error in validation " + getErrorAsString(translatorOutput.getErrorMessages()))
132           .withId("Validation Error").withCategory(ErrorCategory.APPLICATION).build());
133     }
134
135     File file = new File(path + "/VSP.zip");
136     file.createNewFile();
137
138     try (FileOutputStream fos = new FileOutputStream(file)) {
139       ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl();
140       fos.write(
141           toscaFileOutputService.createOutputFile(translatorOutput.getToscaServiceModel(), null));
142     }
143
144     return file;
145   }
146
147   private String getErrorAsString(Map<String, List<ErrorMessage>> errorMessages) {
148     StringBuilder sb = new StringBuilder();
149     errorMessages.entrySet().forEach(
150         entry -> sb.append("File:").append(entry.getKey()).append(System.lineSeparator())
151             .append(getErrorList(entry.getValue())));
152
153     return sb.toString();
154   }
155
156   private String getErrorList(List<ErrorMessage> errors) {
157     StringBuilder sb = new StringBuilder();
158     errors.forEach(
159         error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("]")
160             .append(System.lineSeparator()));
161     return sb.toString();
162   }
163
164 }