Updating licenses in all files
[appc.git] / appc-asdc-listener / appc-yang-generator / src / main / java / org / openecomp / appc / yang / impl / YANGGeneratorImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.yang.impl;
24
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.velocity.Template;
29 import org.apache.velocity.VelocityContext;
30 import org.apache.velocity.app.VelocityEngine;
31 import org.apache.velocity.exception.ParseErrorException;
32 import org.apache.velocity.exception.ResourceNotFoundException;
33 import org.apache.velocity.runtime.RuntimeConstants;
34 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
35 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
36 import org.openecomp.appc.yang.YANGGenerator;
37 import org.openecomp.appc.yang.exception.YANGGenerationException;
38 import org.openecomp.appc.yang.objects.Leaf;
39 import org.openecomp.appc.yang.type.YangTypes;
40 import org.openecomp.sdc.tosca.datatypes.model.NodeType;
41 import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition;
42 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
43 import org.openecomp.sdc.tosca.services.yamlutil.ToscaExtensionYamlUtil;
44
45 import java.io.*;
46 import java.util.HashMap;
47 import java.util.LinkedList;
48 import java.util.List;
49 import java.util.Map;
50
51 @SuppressWarnings("CheckStyle")
52 public class YANGGeneratorImpl implements YANGGenerator {
53
54         private static final EELFLogger Log = EELFManager.getInstance().getLogger(YANGGeneratorImpl.class);
55         private static final String MODULE_TYPE = "moduleType";
56         private static final String LEAVES = "leaves";
57
58
59         /* (non-Javadoc)
60          * @see org.openecomp.appc.yang.YANGGenerator#generateYANG(java.lang.String, java.lang.String, java.io.OutputStream)
61          */
62         @Override
63         public void generateYANG(String uniqueID, String tosca, OutputStream stream)
64                         throws  YANGGenerationException {
65                 Log.info("Entered into generateYANG.");
66                 Log.debug("Received Tosca:\n" + tosca +"\n Received uniqueID:  "+uniqueID);
67
68                 validateInput(uniqueID, tosca, stream);
69                 Map<String,Object> parsedToscaMap = parseTosca(tosca);
70                 String moduleType =parsedToscaMap.get(MODULE_TYPE).toString();
71                 List<Leaf> leaves = (List<Leaf>) parsedToscaMap.get(LEAVES);
72                 VelocityEngine ve = new VelocityEngine();
73                 ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
74                 ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
75                 ve.init();
76                 Template template;
77
78                 try {
79                         template = ve.getTemplate("templates/YangTemplate.vm");
80                 } catch ( ResourceNotFoundException | ParseErrorException ex) {
81                         Log.error("Error while retrieving YANG Template", ex);
82                         throw new YANGGenerationException("Error while retrieving YANG Template",ex);
83                 }
84
85                 VelocityContext vc = new VelocityContext();
86
87                 vc.put("moduleName", uniqueID);
88                 vc.put(MODULE_TYPE, moduleType);
89                 vc.put(LEAVES, leaves);
90
91                 StringWriter sw = new StringWriter();
92                 template.merge(vc,sw);
93                 Log.debug("generated YANG \n "+sw.toString());
94                 try {
95                         String yang = sw.toString();
96                         validateYang(yang);
97                         stream.write(yang.getBytes());
98                         stream.flush();
99                 } catch (IOException e) {
100                         Log.error("Error while writing to outputstream", e);
101                         throw new YANGGenerationException("Error writing to outputstream",e);
102                 } finally {
103                         try {
104                                 stream.close();
105                         } catch (IOException e) {
106                                 Log.error("Error while closing outputstream", e);
107                         }
108                 }
109                 Log.info("exiting generateYANG method.");
110         }
111
112         private void validateYang(String yang) throws YANGGenerationException {
113
114                 try(InputStream inputYangStream = new ByteArrayInputStream(yang.getBytes())){
115                         YangStatementSourceImpl statementSource = new YangStatementSourceImpl(inputYangStream);
116                         if(statementSource.getYangAST()==null){
117                                 throw new YANGGenerationException("Syntax Error in Generated YANG = " + yang);
118                         }
119                 }
120                 catch(IOException e){
121                         Log.error("Error validating yang file "+ yang,e);
122                         throw new YANGGenerationException("Invalid YANG generated",e);
123                 }
124         }
125
126         private Map<String,Object> parseTosca(String tosca) throws YANGGenerationException {
127                 Log.info("Entered into parseTosca.");
128                 ServiceTemplate serviceTemplate = new ToscaExtensionYamlUtil().yamlToObject(tosca, ServiceTemplate.class);
129                 Map<String, NodeType> nodeTypeMap = serviceTemplate.getNode_types();
130                 String kind = nodeTypeMap.keySet().toArray(new String[0])[0];
131                 NodeType nodeType = nodeTypeMap.get(kind);
132                 Map<String,Object> returnMap= new HashMap<>();
133                 Map<String, PropertyDefinition> propertyDefinitionFromTOSCA = nodeType.getProperties();
134                 returnMap.put(MODULE_TYPE, kind);
135                 List<Leaf> leaves =  new LinkedList<>();
136
137                 for(Map.Entry<String, PropertyDefinition> entry: propertyDefinitionFromTOSCA.entrySet()){
138                         Leaf leaf = new Leaf();
139                         leaf.setName(entry.getKey());
140                         PropertyDefinition pd = entry.getValue();
141                         Map<String,String> typeMap=YangTypes.getYangTypeMap();
142                         if (typeMap.containsKey(pd.getType())) {
143                                 String paramType = typeMap.get(pd.getType());
144                                 leaf.setType(paramType);
145                                 leaf.setDescription(!StringUtils.isEmpty(pd.getDescription()) ? pd.getDescription() : "");
146                                 leaf.setMandatory((pd.getRequired() != null) ? Boolean.toString(pd.getRequired()) : Boolean.toString(false));
147                                 leaf.setDefaultValue((pd.get_default() != null) ? pd.get_default().toString(): "");
148                                 leaves.add(leaf);
149                         } else {
150                                 YANGGenerationException yangGenerationException = new YANGGenerationException(pd.getType() + " Type is not supported ", null);
151                                 Log.error(pd.getType() + " Type is not supported ", yangGenerationException);
152                                 throw yangGenerationException;
153                         }
154                 }
155                 returnMap.put(LEAVES, leaves);
156                 Log.info("exiting parseTosca method with return MAP "+returnMap);
157                 return returnMap;
158         }
159
160         private void validateInput(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException {
161                 Log.info("Entered into validateInput.");
162                 if(StringUtils.isEmpty(uniqueID)) {
163                         throw new YANGGenerationException("uniqueID is mandatory, cannot be null or empty.",null);
164                 }
165                 if(StringUtils.isEmpty(tosca)) {
166                         throw new YANGGenerationException("tosca is mandatory, cannot be null or empty.",null);
167                 }
168                 if(stream == null){
169                         throw new YANGGenerationException("stream is mandatory, cannot be null.",null);
170                 }
171                 Log.info("exiting validateInput method.");
172         }
173
174 }