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