2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedInputStream;
25 import java.io.BufferedOutputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.io.PrintWriter;
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.LinkedList;
38 import java.util.List;
40 import java.util.Map.Entry;
42 import java.util.UUID;
43 import java.util.zip.ZipEntry;
44 import java.util.zip.ZipFile;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.servlet.http.HttpServletResponse;
49 import org.apache.commons.compress.utils.IOUtils;
50 import org.apache.commons.fileupload.FileItem;
51 import org.apache.commons.fileupload.FileUploadException;
52 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
53 import org.apache.commons.fileupload.servlet.ServletFileUpload;
54 import org.apache.commons.lang.StringUtils;
55 import org.json.JSONArray;
56 import org.json.JSONObject;
57 import org.onap.policy.common.logging.flexlogger.FlexLogger;
58 import org.onap.policy.common.logging.flexlogger.Logger;
59 import org.onap.policy.rest.XACMLRestProperties;
60 import org.onap.policy.rest.adapter.PolicyRestAdapter;
61 import org.onap.policy.rest.dao.CommonClassDao;
62 import org.onap.policy.rest.jpa.OptimizationModels;
63 import org.onap.policy.rest.jpa.PolicyEntity;
64 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
65 import org.onap.policy.rest.util.MSAttributeObject;
66 import org.onap.policy.rest.util.MSModelUtils;
67 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
68 import org.onap.portalsdk.core.controller.RestrictedBaseController;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.stereotype.Controller;
71 import org.springframework.web.bind.annotation.RequestMapping;
72 import org.springframework.web.servlet.ModelAndView;
74 import com.att.research.xacml.util.XACMLProperties;
75 import com.fasterxml.jackson.core.JsonProcessingException;
76 import com.fasterxml.jackson.databind.DeserializationFeature;
77 import com.fasterxml.jackson.databind.JsonNode;
78 import com.fasterxml.jackson.databind.ObjectMapper;
79 import com.fasterxml.jackson.databind.ObjectWriter;
80 import com.google.gson.Gson;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
85 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
86 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
87 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
88 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
92 public class CreateOptimizationController extends RestrictedBaseController {
93 private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
94 private static CommonClassDao commonClassDao;
96 public static CommonClassDao getCommonClassDao() {
97 return commonClassDao;
100 private OptimizationModels newModel;
101 private String newFile;
102 private String directory;
103 private List<String> modelList = new ArrayList<>();
104 private List<String> dirDependencyList = new ArrayList<>();
105 private LinkedHashMap<String,MSAttributeObject > classMap = new LinkedHashMap<>();
106 String referenceAttributes;
107 String attributeString;
108 Set<String> allManyTrueKeys= new HashSet <>();
110 public static final String DATATYPE = "data_types.policy.data.";
111 public static final String PROPERTIES=".properties.";
112 public static final String TYPE=".type";
113 public static final String STRING="string";
114 public static final String INTEGER="integer";
115 public static final String LIST="list";
116 public static final String DEFAULT=".default";
117 public static final String REQUIRED=".required";
118 public static final String MATCHABLE=".matchable";
119 public static final String MANYFALSE=":MANY-false";
120 public static final String MODEL = "model";
121 public static final String MANY = "MANY-";
122 public static final String UTF8 = "UTF-8";
123 public static final String MODELNAME = "modelName";
124 public static final String APPLICATIONJSON = "application / json";
128 private CreateOptimizationController(CommonClassDao commonClassDao){
129 setCommonClassDao(commonClassDao);
132 public static void setCommonClassDao(CommonClassDao commonClassDao) {
133 CreateOptimizationController.commonClassDao = commonClassDao;
136 public CreateOptimizationController(){
140 protected PolicyRestAdapter policyAdapter = null;
141 private Map<String, String> attributesListRefMap = new HashMap<>();
142 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
143 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
145 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
146 String jsonContent = null;
148 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
150 String tempJson = root.get("policyJSON").toString();
152 //---replace empty value with the value below before calling decodeContent method.
153 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
154 LOGGER.info("dummyValue:" + dummyValue);
155 tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
156 ObjectMapper mapper = new ObjectMapper();
157 JsonNode tempJsonNode = mapper.readTree(tempJson);
158 jsonContent = msController.decodeContent(tempJsonNode).toString();
159 constructJson(policyData, jsonContent, dummyValue);
161 LOGGER.error("Error while decoding microservice content", e);
167 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
168 ObjectWriter om = new ObjectMapper().writer();
170 OptimizationObject optimizationObject = setOptimizationObjectValues(policyAdapter);
172 optimizationObject.setContent(jsonContent);
175 json = om.writeValueAsString(optimizationObject);
176 } catch (JsonProcessingException e) {
177 LOGGER.error("Error writing out the object", e);
179 LOGGER.info("input json: " + json);
180 LOGGER.info("input jsonContent: " + jsonContent);
181 String cleanJson = msController.cleanUPJson(json);
183 //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
184 String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
185 LOGGER.info("tempJson: " + tempJson);
186 cleanJson = msController.removeNullAttributes(tempJson);
187 policyAdapter.setJsonBody(cleanJson);
188 return policyAdapter;
191 @RequestMapping(value={"/policyController/getOptimizationTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
192 public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
193 ObjectMapper mapper = new ObjectMapper();
194 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
195 JsonNode root = mapper.readTree(request.getReader());
197 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
198 String servicename = value.toString().split("-v")[0];
199 String version = null;
200 if (value.toString().contains("-v")){
201 version = value.toString().split("-v")[1];
204 OptimizationModels returnModel = getAttributeObject(servicename, version);
206 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
207 JSONObject jsonHdDefaultObj = null;
208 if(returnHeaderDefauls != null){
209 jsonHdDefaultObj = new JSONObject();
210 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
211 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
212 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
213 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
214 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
217 String headDefautlsData = "";
218 if(jsonHdDefaultObj != null){
219 headDefautlsData = jsonHdDefaultObj.toString();
220 LOGGER.info("returnHeaderDefauls headDefautlsData: " + headDefautlsData);
222 headDefautlsData = "null";
225 //Get all keys with "MANY-true" defined in their value from subAttribute
226 Set<String> allkeys = null;
227 if(returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()){
228 JSONObject json = new JSONObject(returnModel.getSubattributes());
230 allkeys = allManyTrueKeys;
231 allManyTrueKeys = new HashSet <>();
232 LOGGER.info("allkeys : " + allkeys);
235 //Get element order info
236 String dataOrderInfo = returnModel.getDataOrderInfo();
237 String nameOfTrueKeys = "";
239 nameOfTrueKeys = allkeys.toString();
242 String jsonModel = createOptimizationJson(returnModel);
244 JSONObject jsonObject = new JSONObject(jsonModel);
246 JSONObject finalJsonObject = null;
248 Iterator<String> iter = allkeys.iterator();
249 while(iter.hasNext()){
250 //Convert to array values for MANY-true keys
251 finalJsonObject = CreateDcaeMicroServiceController.convertToArrayElement(jsonObject, iter.next());
255 if(finalJsonObject != null){
256 LOGGER.info(finalJsonObject.toString());
257 jsonModel = finalJsonObject.toString();
260 //get all properties with "MANY-true" defined in Ref_attributes
261 Set<String> manyTrueProperties = CreateDcaeMicroServiceController.getManyTrueProperties(returnModel.getRefattributes());
262 JSONObject jsonObj = new JSONObject(jsonModel);
263 for (String s : manyTrueProperties) {
265 //convert to array element for MANY-true properties
266 finalJsonObject = CreateDcaeMicroServiceController.convertToArrayElement(jsonObj, s.trim());
269 if(finalJsonObject != null){
270 LOGGER.info(finalJsonObject.toString());
271 jsonModel = finalJsonObject.toString();
274 response.setCharacterEncoding(UTF8);
275 response.setContentType(APPLICATIONJSON);
276 request.setCharacterEncoding(UTF8);
277 List<Object> list = new ArrayList<>();
278 PrintWriter out = response.getWriter();
279 String responseString = mapper.writeValueAsString(returnModel);
281 if("".equals(nameOfTrueKeys)){
282 j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData +"}");
284 j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData+ "}");
287 out.write(list.toString());
291 @SuppressWarnings({ "rawtypes", "unchecked" })
292 private String createOptimizationJson(OptimizationModels returnModel) {
293 Map<String, String> attributeMap = new HashMap<>();
294 Map<String, String> refAttributeMap = new HashMap<>();
296 String attribute = returnModel.getAttributes();
297 if(attribute != null){
298 attribute = attribute.trim();
300 String refAttribute = returnModel.getRefattributes();
301 if(refAttribute != null){
302 refAttribute = refAttribute.trim();
305 String enumAttribute = returnModel.getEnumValues();
306 if(enumAttribute != null){
307 enumAttribute = enumAttribute.trim();
310 if (!StringUtils.isEmpty(attribute)){
311 attributeMap = CreateDcaeMicroServiceController.convert(attribute, ",");
314 if (!StringUtils.isEmpty(refAttribute)){
315 refAttributeMap = CreateDcaeMicroServiceController.convert(refAttribute, ",");
318 Gson gson = new Gson();
320 String subAttributes = returnModel.getSubattributes();
321 if(subAttributes != null){
322 subAttributes = subAttributes.trim();
327 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
329 JSONObject object = new JSONObject();
332 for (Entry<String, String> keySet : attributeMap.entrySet()){
333 array = new JSONArray();
334 String value = keySet.getValue();
335 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])){
337 object.put(keySet.getKey().trim(), array);
339 object.put(keySet.getKey().trim(), value.trim());
343 for (Entry<String, String> keySet : refAttributeMap.entrySet()){
344 array = new JSONArray();
345 String value = keySet.getValue().split(":")[0];
346 if (gsonObject.containsKey(value)){
347 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])){
348 array.put(recursiveReference(value, gsonObject, enumAttribute));
349 object.put(keySet.getKey().trim(), array);
351 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
354 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])){
355 array.put(value.trim());
356 object.put(keySet.getKey().trim(), array);
358 object.put(keySet.getKey().trim(), value.trim());
363 return object.toString();
366 @SuppressWarnings("unchecked")
367 private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
368 JSONObject object = new JSONObject();
369 Map<String, String> map;
370 Object returnClass = subAttributeMap.get(name);
371 map = (Map<String, String>) returnClass;
374 for( Entry<String, String> m:map.entrySet()){
375 String[] splitValue = m.getValue().split(":");
376 array = new JSONArray();
377 if (subAttributeMap.containsKey(splitValue[0])){
378 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])){
379 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
380 object.put(m.getKey().trim(), array);
382 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
385 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])){
386 array.put(splitValue[0].trim());
387 object.put(m.getKey().trim(), array);
389 object.put(m.getKey().trim(), splitValue[0].trim());
397 //call this method to start the recursive
398 private Set<String> getAllKeys(JSONObject json) {
399 return getAllKeys(json, new HashSet<>());
402 private Set<String> getAllKeys(JSONArray arr) {
403 return getAllKeys(arr, new HashSet<>());
406 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
407 for (int i = 0; i < arr.length(); i++) {
408 Object obj = arr.get(i);
409 if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
410 if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
416 // this method returns a set of keys with "MANY-true" defined in their value.
417 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
418 for (String key : json.keySet()) {
419 Object obj = json.get(key);
420 if(obj instanceof String && ((String) obj).contains("MANY-true")){
421 LOGGER.info("key : " + key);
422 LOGGER.info("obj : " + obj);
423 allManyTrueKeys.add(key);
425 if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
426 if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
432 @RequestMapping(value={"/policyController/getModelServiceVersionData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
433 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
434 ObjectMapper mapper = new ObjectMapper();
435 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
436 JsonNode root = mapper.readTree(request.getReader());
438 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
439 String servicename = value.split("-v")[0];
440 Set<String> returnList = getVersionList(servicename);
442 response.setCharacterEncoding(UTF8);
443 response.setContentType(APPLICATIONJSON);
444 request.setCharacterEncoding(UTF8);
445 List<Object> list = new ArrayList<>();
446 PrintWriter out = response.getWriter();
447 String responseString = mapper.writeValueAsString(returnList);
448 JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString +"}");
450 out.write(list.toString());
454 private Set<String> getVersionList(String name) {
455 OptimizationModels workingModel;
456 Set<String> list = new HashSet<>();
457 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
458 for (int i = 0; i < optimizationModelsData.size(); i++) {
459 workingModel = (OptimizationModels) optimizationModelsData.get(i);
460 if (workingModel.getVersion()!=null){
461 list.add(workingModel.getVersion());
469 private OptimizationModels getAttributeObject(String name, String version) {
470 OptimizationModels workingModel = new OptimizationModels();
471 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
472 for (int i = 0; i < optimizationModelsData.size(); i++) {
473 workingModel = (OptimizationModels) optimizationModelsData.get(i);
475 if (workingModel.getVersion()!=null){
476 if (workingModel.getVersion().equals(version)){
490 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
491 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, MODELNAME, modelName);
494 public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
495 if (policyAdapter.getPolicyData() instanceof PolicyType) {
496 Object policyData = policyAdapter.getPolicyData();
497 PolicyType policy = (PolicyType) policyData;
498 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
499 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") +4);
500 policyAdapter.setPolicyName(policyNameValue);
501 String description = "";
503 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
505 LOGGER.error("Error while collecting the description tag in " + policyNameValue ,e);
506 description = policy.getDescription();
508 policyAdapter.setPolicyDescription(description);
509 // Get the target data under policy.
510 TargetType target = policy.getTarget();
511 if (target != null) {
512 // Under target we have AnyOFType
513 List<AnyOfType> anyOfList = target.getAnyOf();
514 if (anyOfList != null) {
515 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
516 while (iterAnyOf.hasNext()) {
517 AnyOfType anyOf = iterAnyOf.next();
518 // Under AnyOFType we have AllOFType
519 List<AllOfType> allOfList = anyOf.getAllOf();
520 if (allOfList != null) {
521 Iterator<AllOfType> iterAllOf = allOfList.iterator();
522 while (iterAllOf.hasNext()) {
523 AllOfType allOf = iterAllOf.next();
524 // Under AllOFType we have Match
525 List<MatchType> matchList = allOf.getMatch();
526 if (matchList != null) {
527 Iterator<MatchType> iterMatch = matchList.iterator();
528 while (matchList.size()>1 && iterMatch.hasNext()) {
529 MatchType match = iterMatch.next();
531 // Under the match we have attribute value and
532 // attributeDesignator. So,finally down to the actual attribute.
534 AttributeValueType attributeValue = match.getAttributeValue();
535 String value = (String) attributeValue.getContent().get(0);
536 AttributeDesignatorType designator = match.getAttributeDesignator();
537 String attributeId = designator.getAttributeId();
538 // First match in the target is OnapName, so set that value.
539 if ("ONAPName".equals(attributeId)) {
540 policyAdapter.setOnapName(value);
542 if ("RiskType".equals(attributeId)){
543 policyAdapter.setRiskType(value);
545 if ("RiskLevel".equals(attributeId)){
546 policyAdapter.setRiskLevel(value);
548 if ("guard".equals(attributeId)){
549 policyAdapter.setGuard(value);
551 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
552 PolicyController controller = new PolicyController();
553 String newDate = controller.convertDate(value);
554 policyAdapter.setTtlDate(newDate);
557 readFile(policyAdapter, entity);
567 @SuppressWarnings("unchecked")
568 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
569 String policyScopeName = null;
570 ObjectMapper mapper = new ObjectMapper();
572 OptimizationObject optimizationBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), OptimizationObject.class);
573 policyScopeName = msController.getPolicyScope(optimizationBody.getPolicyScope());
574 policyAdapter.setPolicyScope(policyScopeName);
576 policyAdapter.setPriority(optimizationBody.getPriority());
578 if (optimizationBody.getVersion()!= null){
579 policyAdapter.setServiceType(optimizationBody.getService());
580 policyAdapter.setVersion(optimizationBody.getVersion());
582 policyAdapter.setServiceType(optimizationBody.getService());
584 if(optimizationBody.getContent() != null){
585 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
586 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) optimizationBody.getContent();
587 msController.readRecursivlyJSONContent(map, data);
588 policyAdapter.setRuleData(data);
591 } catch (Exception e) {
597 @RequestMapping(value={"/oof_dictionary/set_ModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
598 public void setModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
599 modelList = new ArrayList<>();
600 dirDependencyList = new ArrayList<>();
601 classMap = new LinkedHashMap<>();
602 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
606 String errorMsg = "";
607 for (FileItem item : items) {
608 if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
609 this.newModel = new OptimizationModels();
611 File file = new File(item.getName());
612 OutputStream outputStream = new FileOutputStream(file);
613 IOUtils.copy(item.getInputStream(), outputStream);
614 outputStream.close();
615 this.newFile = file.toString();
616 this.newModel.setModelName(this.newFile.split("-v")[0]);
618 if (this.newFile.contains("-v")){
619 if (item.getName().endsWith(".zip")){
620 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
622 }else if(item.getName().endsWith(".yml")){
623 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
627 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
631 LOGGER.error("Upload error : ", e);
632 errorMsg = "Upload error:" + e.getMessage();
638 if(!errorMsg.isEmpty()){
640 PrintWriter out = response.getWriter();
642 response.setCharacterEncoding(UTF8);
643 response.setContentType(APPLICATIONJSON);
644 request.setCharacterEncoding(UTF8);
646 JSONObject j = new JSONObject();
647 j.put("errorMsg", errorMsg);
648 out.write(j.toString());
652 List<File> fileList = new ArrayList<>();
653 MSModelUtils modelUtil = new MSModelUtils();
654 this.directory = MODEL;
656 extractFolder(this.newFile);
657 fileList = listModelFiles(this.directory);
659 modelUtil.parseTosca(this.newFile);
661 File file = new File(this.newFile);
667 //Process Main Model file first
668 classMap = new LinkedHashMap<>();
669 for (File file : fileList) {
670 if(!file.isDirectory() && file.getName().endsWith(".xmi")){
671 retrieveDependency(file.toString());
675 modelList = createList();
677 msController.cleanUp(this.newFile);
678 msController.cleanUp(directory);
681 modelList.add(this.newModel.getModelName());
682 String className=this.newModel.getModelName();
683 MSAttributeObject optimizationAttributes= new MSAttributeObject();
684 optimizationAttributes.setClassName(className);
686 LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
687 returnAttributeList.put(className, modelUtil.getAttributeString());
688 optimizationAttributes.setAttribute(returnAttributeList);
690 optimizationAttributes.setSubClass(modelUtil.getRetmap());
692 optimizationAttributes.setMatchingSet(modelUtil.getMatchableValues());
694 LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
695 returnReferenceList.put(className, modelUtil.getReferenceAttributes());
696 optimizationAttributes.setRefAttribute(returnReferenceList);
698 if(!"".equals(modelUtil.getListConstraints())){
699 LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
700 String[] listArray=modelUtil.getListConstraints().split("#");
701 for(String str:listArray){
702 String[] strArr= str.split("=");
704 enumList.put(strArr[0], strArr[1]);
707 optimizationAttributes.setEnumType(enumList);
710 classMap=new LinkedHashMap<>();
711 classMap.put(className, optimizationAttributes);
715 PrintWriter out = response.getWriter();
717 response.setCharacterEncoding(UTF8);
718 response.setContentType(APPLICATIONJSON);
719 request.setCharacterEncoding(UTF8);
721 ObjectMapper mapper = new ObjectMapper();
722 JSONObject j = new JSONObject();
723 j.put("classListDatas", modelList);
724 j.put("modelDatas", mapper.writeValueAsString(classMap));
725 j.put("modelType", modelType);
726 j.put("dataOrderInfo", modelUtil.getDataOrderInfo());
728 out.write(j.toString());
732 * Unzip file and store in the model directory for processing
734 @SuppressWarnings("rawtypes")
735 private void extractFolder(String zipFile ) {
737 File file = new File(zipFile);
739 try (ZipFile zip = new ZipFile(file)) {
740 String newPath = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
741 this.directory = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
742 msController.checkZipDirectory(this.directory);
743 new File(newPath).mkdir();
744 Enumeration zipFileEntries = zip.entries();
746 // Process each entry
747 while (zipFileEntries.hasMoreElements()){
748 // grab a zip file entry
749 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
750 String currentEntry = entry.getName();
751 File destFile = new File(MODEL + File.separator + currentEntry);
752 File destinationParent = destFile.getParentFile();
754 destinationParent.mkdirs();
756 if (!entry.isDirectory()){
757 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
759 byte[] data = new byte[BUFFER];
760 try (FileOutputStream fos = new FileOutputStream(destFile);
761 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
762 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
763 dest.write(data, 0, currentByte);
766 } catch (IOException e) {
767 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
769 // PLD should I throw e?
775 if (currentEntry.endsWith(".zip")){
776 extractFolder(destFile.getAbsolutePath());
779 } catch (IOException e) {
780 LOGGER.error("Failed to unzip model file " + zipFile, e);
784 private void retrieveDependency(String workingFile) {
786 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
787 Map<String, MSAttributeObject> tempMap;
789 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
791 classMap.putAll(tempMap);
792 LOGGER.info(tempMap);
798 private List<File> listModelFiles(String directoryName) {
799 File fileDirectory = new File(directoryName);
800 List<File> resultList = new ArrayList<>();
801 File[] fList = fileDirectory.listFiles();
802 for (File file : fList) {
804 resultList.add(file);
805 } else if (file.isDirectory()) {
806 dirDependencyList.add(file.getName());
807 resultList.addAll(listModelFiles(file.getAbsolutePath()));
813 private List<String> createList() {
814 List<String> list = new ArrayList<>();
815 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
816 if (cMap.getValue().isPolicyTempalate()){
817 list.add(cMap.getKey());
823 if (classMap.containsKey(this.newModel.getModelName())){
824 list.add(this.newModel.getModelName());
832 public Map<String, String> getAttributesListRefMap() {
833 return attributesListRefMap;
836 public Map<String, LinkedList<String>> getArrayTextList() {
837 return arrayTextList;
840 private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
841 OptimizationObject optimizationObject = new OptimizationObject();
842 optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
844 if(policyAdapter.getServiceType() !=null){
845 optimizationObject.setService(policyAdapter.getServiceType());
846 optimizationObject.setVersion(policyAdapter.getVersion());
848 if(policyAdapter.getPolicyName()!=null){
849 optimizationObject.setPolicyName(policyAdapter.getPolicyName());
851 if(policyAdapter.getPolicyDescription()!=null){
852 optimizationObject.setDescription(policyAdapter.getPolicyDescription());
854 if (policyAdapter.getPriority()!=null){
855 optimizationObject.setPriority(policyAdapter.getPriority());
857 optimizationObject.setPriority("9999");
859 if (policyAdapter.getRiskLevel()!=null){
860 optimizationObject.setRiskLevel(policyAdapter.getRiskLevel());
862 if (policyAdapter.getRiskType()!=null){
863 optimizationObject.setRiskType(policyAdapter.getRiskType());
865 if (policyAdapter.getGuard()!=null){
866 optimizationObject.setGuard(policyAdapter.getGuard());
868 return optimizationObject;
872 class OptimizationObject {
874 private String service;
875 private String policyName;
876 private String description;
877 private String templateVersion;
878 private String version;
879 private String priority;
880 private String policyScope;
881 private String riskType;
882 private String riskLevel;
883 private String guard = null;
885 public String getGuard() {
888 public void setGuard(String guard) {
891 public String getRiskType() {
894 public void setRiskType(String riskType) {
895 this.riskType = riskType;
897 public String getRiskLevel() {
900 public void setRiskLevel(String riskLevel) {
901 this.riskLevel = riskLevel;
903 public String getPriority() {
906 public void setPriority(String priority) {
907 this.priority = priority;
909 public String getPolicyScope() {
912 public void setPolicyScope(String policyScope) {
913 this.policyScope = policyScope;
915 public String getVersion() {
918 public void setVersion(String version) {
919 this.version = version;
921 private Object content;
923 public String getPolicyName() {
926 public void setPolicyName(String policyName) {
927 this.policyName = policyName;
929 public String getDescription() {
932 public void setDescription(String description) {
933 this.description = description;
935 public Object getContent() {
938 public void setContent(Object content) {
939 this.content = content;
941 public String getService() {
944 public void setService(String service) {
945 this.service = service;
947 public String getTemplateVersion() {
948 return templateVersion;
950 public void setTemplateVersion(String templateVersion) {
951 this.templateVersion = templateVersion;