Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-REST / src / main / java / org / openecomp / policy / rest / util / MSModelUtitils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-REST
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.policy.rest.util;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.eclipse.emf.common.util.EList;
37 import org.eclipse.emf.common.util.TreeIterator;
38 import org.eclipse.emf.ecore.EAnnotation;
39 import org.eclipse.emf.ecore.EClass;
40 import org.eclipse.emf.ecore.EClassifier;
41 import org.eclipse.emf.ecore.EEnum;
42 import org.eclipse.emf.ecore.EObject;
43 import org.eclipse.emf.ecore.EPackage;
44 import org.eclipse.emf.ecore.EReference;
45 import org.eclipse.emf.ecore.EStructuralFeature;
46
47 import org.json.JSONObject;
48 import org.openecomp.policy.rest.XACMLRestProperties;
49
50 import com.att.research.xacml.util.XACMLProperties;
51
52 import org.eclipse.emf.common.util.URI;
53 import org.eclipse.emf.ecore.resource.Resource;
54 import org.eclipse.emf.ecore.resource.ResourceSet;
55 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
56 import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
57
58
59 public class MSModelUtitils {
60         
61         private static final Log logger = LogFactory.getLog(MSModelUtitils.class);
62  
63         private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
64
65         public HashMap<String, MSAttributeObject> processEpackage(String xmiFile){
66                 EPackage root = getEpackage(xmiFile);
67             TreeIterator<EObject> treeItr = root.eAllContents();
68             String className = null;
69             String returnValue = null;
70             
71                 //    Pulling out dependency from file
72             while (treeItr.hasNext()) {     
73                 EObject obj = (EObject) treeItr.next();
74                 if (obj instanceof EClassifier) {
75                         EClassifier eClassifier = (EClassifier) obj;
76                         className = eClassifier.getName();
77                         
78                         if (obj instanceof EEnum) {
79                         //      getEEnum();
80                                 returnValue = null;
81                         }else if (obj instanceof EClass) {
82                                 String temp = getDependencyList(eClassifier, className).toString();
83                                 returnValue = StringUtils.replaceEach(temp, new String[]{"[", "]"}, new String[]{"", ""});
84                                 getAttributes(className, returnValue, root);
85                         }                                       
86                 }
87             }
88             return classMap;
89         }
90
91         private EPackage getEpackage(String xmiFile) {
92                 ResourceSet resSet = new ResourceSetImpl();
93             Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
94             Map<String, Object> m = reg.getExtensionToFactoryMap();
95             m.put("xmi", new XMIResourceFactoryImpl());
96             Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true);
97             try {
98                         resource.load(Collections.EMPTY_MAP);
99                 } catch (IOException e) {
100                         logger.error("Error loading Encore Resource for new Model");
101                 }
102             
103             EPackage root = (EPackage) resource.getContents().get(0);
104
105                 return root;
106         }
107
108         private void getEEnum() {
109                 
110         }
111         
112         public void getAttributes(String className, String dependency, EPackage root) {
113                 List<String> dpendList = null;
114             if (dependency!=null){
115                 dpendList = new ArrayList<String>(Arrays.asList(dependency.split(",")));
116             }
117                 MSAttributeObject msAttributeObject = new MSAttributeObject();
118                 msAttributeObject.setClassName(className);
119                 HashMap<String, String> returnRefList = getRefAttributeList(root, className);
120                 HashMap<String, String> returnAttributeList = getAttributeList(root, className);
121                 HashMap<String, String> returnSubList = getSubAttributeList(root, className);
122                 msAttributeObject.setAttribute(returnAttributeList);
123                 msAttributeObject.setRefAttribute(returnRefList);
124                 msAttributeObject.setSubClass(returnSubList);
125                 msAttributeObject.setDependency(dpendList.toString());
126                 this.classMap.put(className, msAttributeObject);        
127         }
128         
129         private HashMap<String, String> getSubAttributeList(EPackage root, String className) {
130             //EPackage root = (EPackage) resource.getContents().get(0);
131             TreeIterator<EObject> treeItr = root.eAllContents();
132             boolean requiredAttribute = false; 
133             HashMap<String, String> subAttribute = new HashMap<String, String>();
134             int rollingCount = 0;
135             int processClass = 0;
136             boolean annotation = false;
137                     
138                 //    Pulling out dependency from file
139             while (treeItr.hasNext() && rollingCount < 2) {      
140                 
141                 EObject obj = treeItr.next();
142                 if (obj instanceof EClassifier) {
143                         requiredAttribute = isRequiredAttribute(obj,  className);       
144                         if (requiredAttribute){
145                                 processClass++;
146                         }
147                         rollingCount = rollingCount+processClass;
148                         }
149                         
150                 if (requiredAttribute)   {
151                         if (obj instanceof EStructuralFeature) {
152                                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
153                                 if (eStrucClassifier.getEAnnotations().size() != 0) {
154                                         annotation = testAnnotation(eStrucClassifier);
155                                                 if (annotation &&  obj instanceof EReference) {
156                                                         EClass refType = ((EReference) obj).getEReferenceType();
157                                         //              String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
158                                                         if(!refType.toString().contains("eProxyURI:")){
159                                                                 subAttribute.put(eStrucClassifier.getName(), refType.getName());                                                
160                                                         }
161                                                 }       
162                                 }
163                         }
164                }
165             }
166                 return subAttribute;
167         }
168         
169         public String checkDefultValue(String defultValue) {
170                 if (defultValue!=null){
171                         return ":defaultValue-"+ defultValue;
172                 }
173                 return ":defaultValue-NA";
174                 
175         }
176         
177         public String checkRequiredPattern(int upper, int lower) {      
178                 String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN);
179                 
180                 if (pattern!=null){
181                         if (upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){
182                                 return ":required-true";
183                         }
184                 }
185                                 
186                 return ":required-false";
187         }
188         
189         public JSONObject buildJavaObject(HashMap<String, String> map, String attributeType){
190
191                 JSONObject returnValue = new JSONObject(map);
192                 
193                 return returnValue;
194                 
195         }
196         
197         public HashMap<String, String> getRefAttributeList(EPackage root, String className){
198             
199             TreeIterator<EObject> treeItr = root.eAllContents();
200             boolean requiredAttribute = false; 
201             HashMap<String, String> refAttribute = new HashMap<String, String>();
202             int rollingCount = 0;
203             int processClass = 0;
204             boolean annotation = false;
205                     
206                 //    Pulling out dependency from file
207             while (treeItr.hasNext()) {     
208                 EObject obj = treeItr.next();
209                 if (obj instanceof EClassifier) {
210                         requiredAttribute = isRequiredAttribute(obj,  className);       
211                         if (requiredAttribute){
212                                 processClass++;
213                         }
214                         rollingCount = rollingCount+processClass;
215                         }
216                         
217                 if (requiredAttribute)   {
218                         if (obj instanceof EStructuralFeature) {
219                                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
220                                 if (eStrucClassifier.getEAnnotations().size() != 0) {
221                                         annotation = testAnnotation(eStrucClassifier);
222                                                 if ( annotation &&  obj instanceof EReference) {
223                                                         EClass refType = ((EReference) obj).getEReferenceType();
224                                                         if(refType.toString().contains("eProxyURI:")){
225                                                                 String one = refType.toString().split("eProxyURI:")[1];
226                                                                 String refValue = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""});                                                    
227                                                                 refAttribute.put(eStrucClassifier.getName(), refValue);                                                 
228                                                         } else {
229                                                                 String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
230                                                                 if (array.contains("false")){
231                                                                         array = "";
232                                                                 }
233                                                                 refAttribute.put(eStrucClassifier.getName(), refType.getName() + array);
234                                                         }
235                                                 }       
236                                 }
237                         }
238                }
239             }
240                 return refAttribute;
241         }
242         
243         private boolean testAnnotation(EStructuralFeature eStrucClassifier) {
244                 String annotationType = null;
245                 EAnnotation eAnnotation = null;
246                 String ecompType = null;
247                 
248                 EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
249                 
250                 for (int i = 0; i < value.size(); i++){
251                         annotationType = value.get(i).getSource();
252                         eAnnotation = eStrucClassifier.getEAnnotations().get(i);
253                         ecompType = eAnnotation.getDetails().get(0).getValue();
254                         if (annotationType.contains("http://localhost.com") && ecompType.contains("configuration")){
255                                 return true;
256                         }
257                 }
258
259                 return false;
260         }
261
262         public boolean isRequiredAttribute(EObject obj, String className){
263         EClassifier eClassifier = (EClassifier) obj;
264         String workingClass = eClassifier.getName();
265         workingClass.trim();
266                 if (workingClass.equalsIgnoreCase(className)){
267                         return  true;
268                 }
269
270                 return false;
271         }
272
273         public HashMap<String, String> getAttributeList(EPackage root, String className){
274             
275             TreeIterator<EObject> treeItr = root.eAllContents();
276             boolean reference = false;
277             boolean requiredAttribute = false; 
278             HashMap<String, String> refAttribute = new HashMap<String, String>();
279             String workingClass = null;
280             boolean annotation = false;
281                     
282                 //    Pulling out dependency from file
283             while (treeItr.hasNext()) {     
284                 reference = false;
285                 EObject obj = treeItr.next();
286                 if (obj instanceof EClassifier) {
287                         requiredAttribute = isRequiredAttribute(obj,  className );
288                         }
289                           
290                 if (requiredAttribute){
291                         if (obj instanceof EStructuralFeature) {
292                                 EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
293                                 if (eStrucClassifier.getEAnnotations().size() != 0) {
294                                         annotation = testAnnotation(eStrucClassifier);
295                                                 if (annotation && !(obj instanceof EReference)) {
296                                                         String name = eStrucClassifier.getName();
297                                                         String defaultValue = checkDefultValue(((EStructuralFeature) obj).getDefaultValueLiteral());
298                                                         String eType = eStrucClassifier.getEType().getInstanceClassName();
299                                                         String array = arrayCheck(((EStructuralFeature) obj).getUpperBound());
300                                                         String required = checkRequiredPattern(((EStructuralFeature) obj).getUpperBound(), ((EStructuralFeature) obj).getLowerBound());
301                                                         String attributeValue =  eType + defaultValue + required + array;
302                                                         refAttribute.put(name, attributeValue); 
303                                                 }
304                                 }
305                     }
306                 }
307             }
308                 return refAttribute;
309                 
310         }
311         
312         public String arrayCheck(int upperBound) {
313                 
314                 if (upperBound == -1){
315                         return ":MANY-true";
316                 }
317                 
318                 return ":MANY-false";
319         }
320         
321         public List<String> getDependencyList(EClassifier eClassifier, String className){
322                 List<String> returnValue = new ArrayList<>();;
323                 EList<EClass> somelist = ((EClass) eClassifier).getEAllSuperTypes();
324                 if (somelist.isEmpty()){
325                         return returnValue;
326                 }
327                 for(EClass depend: somelist){
328                         if (depend.toString().contains("eProxyURI:")){
329                                 String one = depend.toString().split("eProxyURI:")[1];
330                                 String value = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""});
331                                 returnValue.add(value);
332                         }
333                 }
334
335                 return returnValue;
336         }
337         
338         public String createJson(HashMap<String, String> subClassAttributes, HashMap<String, MSAttributeObject> classMap, String className) {
339                 String json = "";
340                 JSONObject jsonObj; 
341                 
342                 jsonObj = new JSONObject();
343                 
344                 Map<String, String> missingValues = new HashMap<String, String>();
345                 Map<String, String> workingMap = new HashMap<String, String>();
346                 
347                 for ( Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()){
348                         String value = map.getValue().split(":")[0];
349                         if (value!=null){
350                                 workingMap =  classMap.get(value).getRefAttribute();
351                                 for ( Entry<String, String> subMab : workingMap.entrySet()){
352                                         String value2 = subMab.getValue().split(":")[0];
353                                         if (!subClassAttributes.containsValue(value2)){
354                                                 missingValues.put(subMab.getKey(), subMab.getValue());
355                                                 classMap.get(value).addAttribute(subMab.getKey(), subMab.getValue());
356                                         }
357                                 }
358                                 
359                         }
360                 }
361                 
362                 if (!missingValues.isEmpty()){
363                         for (Entry<String, String> addValue : missingValues.entrySet()){
364                                 subClassAttributes.put(addValue.getKey(), addValue.getValue().split(":")[0]);
365                         }
366                 }
367                 
368                 for ( Map.Entry<String, String>  map : subClassAttributes.entrySet()){
369                         jsonObj.put(map.getValue().split(":")[0], classMap.get(map.getValue().split(":")[0]).getAttribute());   
370                 }
371                 
372                 if (logger.isDebugEnabled()) {
373                         logger.debug("Json value: " + jsonObj);
374                 }
375                 
376                 return jsonObj.toString();              
377         }
378         
379         public String createSubAttributes(ArrayList<String> dependency, HashMap<String, MSAttributeObject> classMap, String modelName) {
380                 
381                 HashMap <String,  String>  workingMap = new HashMap<String,String>();
382                 MSAttributeObject tempObject = new MSAttributeObject(); 
383                 HashMap <String, String> refAttribute =  new HashMap<String,String>();
384                  HashMap <String,  String>  workingSubMap = new HashMap<String,String>();
385                 Map<String, String> tempPefAttribute = null;
386                 LinkedList linkedList = new LinkedList();
387                 String addedValue = null;
388                 
389                 boolean addingValues = false;
390                 
391                 if (dependency!=null){
392                         if (dependency.size()==0){
393                                 return "{}";
394                         }       
395                         dependency.add(modelName);
396                         for (String element: dependency){
397                                 tempObject = classMap.get(element);
398                                 if (tempObject!=null){
399                                         workingMap.putAll(classMap.get(element).getSubClass());
400                             //        workingSubMap = CheckForSecondSubClass(classMap.get(element).getSubClass(), classMap);
401                              //       if (workingSubMap!=null){
402                             //            workingMap.putAll(workingSubMap);
403                            //         }
404                                 }
405                         }
406                 }
407                 
408                 String returnValue = createJson(workingMap, classMap, modelName);                       
409                 return returnValue;
410         }
411
412     private HashMap<String, String> CheckForSecondSubClass(HashMap<String, String> subClass, HashMap<String, MSAttributeObject> mainMap) {
413         MSAttributeObject tempObject = new MSAttributeObject(); 
414         HashMap<String, String> subClassValue = new HashMap<String,String>();
415         
416         for (Entry<String, String> classSet : subClass.entrySet()){
417             String key = classSet.getKey();
418             String value = classSet.getValue();
419             tempObject = mainMap.get(value);
420             subClassValue = tempObject.getSubClass();
421             if (subClassValue!=null){
422                 return subClassValue;
423             }
424         }
425         return null;
426         
427     }
428     
429         public ArrayList<String> getFullDependencyList(ArrayList<String> dependency, HashMap<String,MSAttributeObject > classMap) {
430                 ArrayList<String> returnList = new ArrayList<String>();
431                 ArrayList<String> workingList = new ArrayList<String>();
432                 int i = 0;
433                 MSAttributeObject newDepend = null;
434                 returnList.addAll(dependency);
435                 for (String element : dependency ){
436                         if (classMap.containsKey(element)){
437                                 MSAttributeObject value = classMap.get(element);
438                                 String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""});
439                                 workingList = new ArrayList<String>(Arrays.asList(rawValue.split(",")));        
440                                 for(String depend : workingList){
441                                         if (!returnList.contains(depend) && !depend.isEmpty()){
442                                                 returnList.add(depend.trim());
443                                         }
444                                 }
445                         }
446                 }
447                 
448                 return returnList;
449         }
450 }