4aaa9a8a0335a53f7884000fb48cfd048e0b303b
[sdc.git] /
1 /*
2  * Copyright © 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.vendorsoftwareproduct.services.schemagenerator;
18
19 import freemarker.template.Template;
20 import freemarker.template.TemplateException;
21 import org.openecomp.sdc.common.errors.CoreException;
22 import org.openecomp.sdc.common.errors.ErrorCategory;
23 import org.openecomp.sdc.common.errors.ErrorCode;
24 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType;
25 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext;
26 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput;
27
28 import java.io.IOException;
29 import java.io.StringWriter;
30 import java.io.Writer;
31
32 public class SchemaGenerator {
33   public static final String SCHEMA_GENERATION_ERROR = "SCHEMA_GENERATION_ERROR";
34   private SchemaGenerator() {
35     // Utility classes, which are a collection of static members, are not meant to be instantiated
36   }
37
38   /**
39    * Generate string.
40    *
41    * @param schemaTemplateContext the schema template context
42    * @param entityType            the entity type
43    * @param input                 the input
44    * @return the string
45    */
46   public static String generate(SchemaTemplateContext schemaTemplateContext,
47                                 CompositionEntityType entityType, SchemaTemplateInput input) {
48     Template schemaTemplate =
49         SchemaGeneratorConfig.getSchemaTemplate(schemaTemplateContext, entityType);
50     return processTemplate(input, schemaTemplate);
51   }
52
53   private static String processTemplate(SchemaTemplateInput input, Template schemaTemplate) {
54     try (Writer writer = new StringWriter(1024)) {
55       schemaTemplate.process(input, writer);
56       return writer.toString();
57     } catch (IOException | TemplateException exception) {
58       throw new CoreException(
59           new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION)
60               .withId(SCHEMA_GENERATION_ERROR).withMessage(exception.getMessage()).build(), exception);
61     }
62   }
63 }