2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-2019 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;
23 import com.att.research.xacml.util.XACMLProperties;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.DeserializationFeature;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import com.fasterxml.jackson.databind.ObjectWriter;
29 import com.google.gson.Gson;
31 import java.io.BufferedInputStream;
32 import java.io.BufferedOutputStream;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.OutputStream;
37 import java.util.ArrayList;
38 import java.util.Enumeration;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.LinkedHashMap;
43 import java.util.LinkedList;
44 import java.util.List;
46 import java.util.Map.Entry;
48 import java.util.UUID;
49 import java.util.zip.ZipEntry;
50 import java.util.zip.ZipFile;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
62 import org.apache.commons.compress.utils.IOUtils;
63 import org.apache.commons.fileupload.FileItem;
64 import org.apache.commons.fileupload.FileUploadException;
65 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
66 import org.apache.commons.fileupload.servlet.ServletFileUpload;
67 import org.apache.commons.lang.StringUtils;
68 import org.json.JSONArray;
69 import org.json.JSONObject;
70 import org.onap.policy.common.logging.flexlogger.FlexLogger;
71 import org.onap.policy.common.logging.flexlogger.Logger;
72 import org.onap.policy.rest.XacmlRestProperties;
73 import org.onap.policy.rest.adapter.PolicyRestAdapter;
74 import org.onap.policy.rest.dao.CommonClassDao;
75 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
76 import org.onap.policy.rest.jpa.OptimizationModels;
77 import org.onap.policy.rest.jpa.PolicyEntity;
78 import org.onap.policy.rest.util.MsAttributeObject;
79 import org.onap.policy.rest.util.MsModelUtils;
80 import org.onap.policy.rest.util.MsModelUtils.ModelType;
81 import org.onap.policy.utils.PolicyUtils;
82 import org.onap.portalsdk.core.controller.RestrictedBaseController;
83 import org.springframework.beans.factory.annotation.Autowired;
84 import org.springframework.stereotype.Controller;
85 import org.springframework.web.bind.annotation.RequestMapping;
86 import org.springframework.web.servlet.ModelAndView;
90 public class CreateOptimizationController extends RestrictedBaseController {
91 private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
93 private static final int BUFFER = 2048;
95 private static CommonClassDao commonClassDao;
97 public static CommonClassDao getCommonClassDao() {
98 return commonClassDao;
101 private OptimizationModels newModel;
102 private String newFile;
103 private String directory;
104 private List<String> modelList = new ArrayList<>();
105 private List<String> dirDependencyList = new ArrayList<>();
106 private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
107 String referenceAttributes;
108 String attributeString;
109 Set<String> allManyTrueKeys = new HashSet<>();
111 public static final String DATATYPE = "data_types.policy.data.";
112 public static final String PROPERTIES = ".properties.";
113 public static final String TYPE = ".type";
114 public static final String STRING = "string";
115 public static final String INTEGER = "integer";
116 public static final String LIST = "list";
117 public static final String DEFAULT = ".default";
118 public static final String REQUIRED = ".required";
119 public static final String MATCHABLE = ".matchable";
120 public static final String MANYFALSE = ":MANY-false";
121 public static final String MODEL = "model";
122 public static final String MANY = "MANY-";
123 public static final String MODELNAME = "modelName";
126 private CreateOptimizationController(CommonClassDao commonClassDao) {
127 setCommonClassDao(commonClassDao);
130 public static void setCommonClassDao(CommonClassDao commonClassDao) {
131 CreateOptimizationController.commonClassDao = commonClassDao;
134 public CreateOptimizationController() {
138 protected PolicyRestAdapter policyAdapter = null;
139 private Map<String, String> attributesListRefMap = new HashMap<>();
140 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
141 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
144 * setDataToPolicyRestAdapter.
146 * @param policyData PolicyRestAdapter
147 * @param root JsonNode
148 * @return PolicyRestAdapter
150 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
151 String jsonContent = null;
153 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
155 String tempJson = root.get("policyJSON").toString();
157 // ---replace empty value with the value below before calling decodeContent method.
158 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
159 LOGGER.info("dummyValue:" + dummyValue);
161 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
162 ObjectMapper mapper = new ObjectMapper();
163 JsonNode tempJsonNode = mapper.readTree(tempJson);
164 jsonContent = msController.decodeContent(tempJsonNode).toString();
165 constructJson(policyData, jsonContent, dummyValue);
166 } catch (Exception e) {
167 LOGGER.error("Error while decoding microservice content", e);
173 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
174 ObjectWriter om = new ObjectMapper().writer();
176 OptimizationObject optimizationObject = setOptimizationObjectValues(policyAdapter);
178 optimizationObject.setContent(jsonContent);
181 json = om.writeValueAsString(optimizationObject);
182 } catch (JsonProcessingException e) {
183 LOGGER.error("Error writing out the object", e);
185 LOGGER.info("input json: " + json);
186 LOGGER.info("input jsonContent: " + jsonContent);
187 String cleanJson = msController.cleanUpJson(json);
189 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
191 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
192 LOGGER.info("tempJson: " + tempJson);
193 cleanJson = msController.removeNullAttributes(tempJson);
194 policyAdapter.setJsonBody(cleanJson);
195 return policyAdapter;
199 * getOptimizationTemplateData.
201 * @param request HttpServletRequest
202 * @param response HttpServletResponse
203 * @return ModelAndView
204 * @throws IOException IOException
207 value = {"/policyController/getOptimizationTemplateData.htm"},
208 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
209 public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
211 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
212 ObjectMapper mapper = new ObjectMapper();
213 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
214 JsonNode root = mapper.readTree(request.getReader());
216 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
217 String servicename = value.split("-v")[0];
218 String version = null;
219 if (value.contains("-v")) {
220 version = value.split("-v")[1];
223 OptimizationModels returnModel = getAttributeObject(servicename, version);
225 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
226 JSONObject jsonHdDefaultObj = null;
227 if (returnHeaderDefauls != null) {
228 jsonHdDefaultObj = new JSONObject();
229 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
230 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
231 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
232 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
233 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
236 String headDefautlsData = "";
237 if (jsonHdDefaultObj != null) {
238 headDefautlsData = jsonHdDefaultObj.toString();
239 LOGGER.info("returnHeaderDefauls headDefautlsData: " + headDefautlsData);
241 headDefautlsData = "null";
244 // Get all keys with "MANY-true" defined in their value from subAttribute
245 Set<String> allkeys = null;
246 if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
247 getAllKeys(new JSONObject(returnModel.getSubattributes()));
248 allkeys = allManyTrueKeys;
249 allManyTrueKeys = new HashSet<>();
250 LOGGER.info("allkeys : " + allkeys);
253 // Get element order info
254 String dataOrderInfo = returnModel.getDataOrderInfo();
255 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
256 dataOrderInfo = "\"" + dataOrderInfo + "\"";
259 String nameOfTrueKeys = "";
260 if (allkeys != null) {
261 nameOfTrueKeys = allkeys.toString();
264 String jsonModel = createOptimizationJson(returnModel);
266 JSONObject jsonObject = new JSONObject(jsonModel);
268 JSONObject finalJsonObject = null;
269 if (allkeys != null) {
270 Iterator<String> iter = allkeys.iterator();
271 while (iter.hasNext()) {
272 // Convert to array values for MANY-true keys
273 finalJsonObject = controller.convertToArrayElement(jsonObject, iter.next());
277 if (finalJsonObject != null) {
278 LOGGER.info(finalJsonObject.toString());
279 jsonModel = finalJsonObject.toString();
282 // get all properties with "MANY-true" defined in Ref_attributes
283 Set<String> manyTrueProperties = controller.getManyTrueProperties(returnModel.getRefattributes());
284 JSONObject jsonObj = new JSONObject(jsonModel);
285 for (String s : manyTrueProperties) {
287 // convert to array element for MANY-true properties
288 finalJsonObject = controller.convertToArrayElement(jsonObj, s.trim());
291 if (finalJsonObject != null) {
292 LOGGER.info(finalJsonObject.toString());
293 jsonModel = finalJsonObject.toString();
296 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
297 response.setContentType(PolicyUtils.APPLICATION_JSON);
298 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
299 List<Object> list = new ArrayList<>();
300 String responseString = mapper.writeValueAsString(returnModel);
301 JSONObject json = null;
302 if ("".equals(nameOfTrueKeys)) {
303 json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
304 + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
306 json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
307 + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
308 + headDefautlsData + "}");
311 response.getWriter().write(list.toString());
315 @SuppressWarnings({"rawtypes", "unchecked"})
316 private String createOptimizationJson(OptimizationModels returnModel) {
317 Map<String, String> attributeMap = new HashMap<>();
318 Map<String, String> refAttributeMap = new HashMap<>();
320 String attribute = returnModel.getAttributes();
321 if (attribute != null) {
322 attribute = attribute.trim();
324 String refAttribute = returnModel.getRefattributes();
325 if (refAttribute != null) {
326 refAttribute = refAttribute.trim();
329 String enumAttribute = returnModel.getEnumValues();
330 if (enumAttribute != null) {
331 enumAttribute = enumAttribute.trim();
334 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
335 if (!StringUtils.isEmpty(attribute)) {
336 attributeMap = controller.convert(attribute, ",");
339 if (!StringUtils.isEmpty(refAttribute)) {
340 refAttributeMap = controller.convert(refAttribute, ",");
343 Gson gson = new Gson();
345 String subAttributes = returnModel.getSubattributes();
346 if (subAttributes != null) {
347 subAttributes = subAttributes.trim();
352 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
354 JSONObject object = new JSONObject();
357 for (Entry<String, String> keySet : attributeMap.entrySet()) {
358 array = new JSONArray();
359 String value = keySet.getValue();
360 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
362 object.put(keySet.getKey().trim(), array);
364 object.put(keySet.getKey().trim(), value.trim());
368 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
369 array = new JSONArray();
370 String value = keySet.getValue().split(":")[0];
371 if (gsonObject.containsKey(value)) {
372 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
373 array.put(recursiveReference(value, gsonObject, enumAttribute));
374 object.put(keySet.getKey().trim(), array);
376 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
379 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
380 array.put(value.trim());
381 object.put(keySet.getKey().trim(), array);
383 object.put(keySet.getKey().trim(), value.trim());
388 return object.toString();
391 @SuppressWarnings("unchecked")
392 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
393 JSONObject object = new JSONObject();
394 Map<String, String> map;
395 Object returnClass = subAttributeMap.get(name);
396 map = (Map<String, String>) returnClass;
399 for (Entry<String, String> m : map.entrySet()) {
400 String[] splitValue = m.getValue().split(":");
401 array = new JSONArray();
402 if (subAttributeMap.containsKey(splitValue[0])) {
403 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
404 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
405 object.put(m.getKey().trim(), array);
407 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
410 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
411 array.put(splitValue[0].trim());
412 object.put(m.getKey().trim(), array);
414 object.put(m.getKey().trim(), splitValue[0].trim());
422 // call this method to start the recursive
423 private Set<String> getAllKeys(JSONObject json) {
424 return getAllKeys(json, new HashSet<>());
427 private Set<String> getAllKeys(JSONArray arr) {
428 return getAllKeys(arr, new HashSet<>());
431 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
432 for (int i = 0; i < arr.length(); i++) {
433 Object obj = arr.get(i);
434 if (obj instanceof JSONObject) {
435 keys.addAll(getAllKeys(arr.getJSONObject(i)));
437 if (obj instanceof JSONArray) {
438 keys.addAll(getAllKeys(arr.getJSONArray(i)));
445 // this method returns a set of keys with "MANY-true" defined in their value.
446 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
447 for (String key : json.keySet()) {
448 Object obj = json.get(key);
449 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
450 LOGGER.info("key : " + key);
451 LOGGER.info("obj : " + obj);
452 allManyTrueKeys.add(key);
454 if (obj instanceof JSONObject) {
455 keys.addAll(getAllKeys(json.getJSONObject(key)));
457 if (obj instanceof JSONArray) {
458 keys.addAll(getAllKeys(json.getJSONArray(key)));
466 * getModelServiceVersionData.
468 * @param request HttpServletRequest
469 * @param response HttpServletResponse
470 * @return ModelAndView
471 * @throws IOException IOException
474 value = {"/policyController/getModelServiceVersionData.htm"},
475 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
476 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
478 ObjectMapper mapper = new ObjectMapper();
479 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
480 JsonNode root = mapper.readTree(request.getReader());
482 final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
483 final String servicename = value.split("-v")[0];
485 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
486 response.setContentType(PolicyUtils.APPLICATION_JSON);
487 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
488 List<Object> list = new ArrayList<>();
489 list.add(new JSONObject("{optimizationModelVersionData: "
490 + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
491 response.getWriter().write(list.toString());
495 private Set<String> getVersionList(String name) {
496 OptimizationModels workingModel;
497 Set<String> list = new HashSet<>();
498 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
499 for (int i = 0; i < optimizationModelsData.size(); i++) {
500 workingModel = (OptimizationModels) optimizationModelsData.get(i);
501 if (workingModel.getVersion() != null) {
502 list.add(workingModel.getVersion());
510 private OptimizationModels getAttributeObject(String name, String version) {
511 OptimizationModels workingModel = new OptimizationModels();
512 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
513 for (int i = 0; i < optimizationModelsData.size(); i++) {
514 workingModel = (OptimizationModels) optimizationModelsData.get(i);
515 if (version != null) {
516 if (workingModel.getVersion() != null) {
517 if (workingModel.getVersion().equals(version)) {
531 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
532 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, MODELNAME,
537 * prePopulatePolicyData.
539 * @param policyAdapter PolicyRestAdapter
540 * @param entity PolicyEntity
542 public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
543 if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
546 Object policyData = policyAdapter.getPolicyData();
547 PolicyType policy = (PolicyType) policyData;
548 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
549 String policyNameValue =
550 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
551 policyAdapter.setPolicyName(policyNameValue);
552 String description = "";
554 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
555 } catch (Exception e) {
556 LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
557 description = policy.getDescription();
559 policyAdapter.setPolicyDescription(description);
560 // Get the target data under policy.
561 TargetType target = policy.getTarget();
562 if (target == null) {
565 for (AnyOfType anyOf : target.getAnyOf()) {
566 for (AllOfType allOf : anyOf.getAllOf()) {
567 for (MatchType match : allOf.getMatch()) {
569 // Under the match we have attribute value and
570 // attributeDesignator. So,finally down to the actual attribute.
572 policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
573 (String) match.getAttributeValue().getContent().get(0));
575 readFile(policyAdapter, entity);
580 @SuppressWarnings("unchecked")
581 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
582 String policyScopeName = null;
583 ObjectMapper mapper = new ObjectMapper();
585 OptimizationObject optimizationBody =
586 mapper.readValue(entity.getConfigurationData().getConfigBody(), OptimizationObject.class);
587 policyScopeName = msController.getPolicyScope(optimizationBody.getPolicyScope());
588 policyAdapter.setPolicyScope(policyScopeName);
590 policyAdapter.setPriority(optimizationBody.getPriority());
592 if (optimizationBody.getVersion() != null) {
593 policyAdapter.setServiceType(optimizationBody.getService());
594 policyAdapter.setVersion(optimizationBody.getVersion());
596 policyAdapter.setServiceType(optimizationBody.getService());
598 if (optimizationBody.getContent() != null) {
599 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
600 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) optimizationBody.getContent();
601 msController.readRecursivlyJSONContent(map, data);
602 policyAdapter.setRuleData(data);
605 } catch (Exception e) {
614 * @param request HttpServletRequest
615 * @param response HttpServletResponse
616 * @throws IOException IOException
617 * @throws FileUploadException FileUploadException
620 value = {"/oof_dictionary/set_ModelData"},
621 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
622 public void setModelData(HttpServletRequest request, HttpServletResponse response)
623 throws IOException, FileUploadException {
624 modelList = new ArrayList<>();
625 dirDependencyList = new ArrayList<>();
626 classMap = new LinkedHashMap<>();
627 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
631 String errorMsg = "";
632 for (FileItem item : items) {
633 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
634 this.newModel = new OptimizationModels();
636 File file = new File(item.getName());
637 OutputStream outputStream = new FileOutputStream(file);
638 IOUtils.copy(item.getInputStream(), outputStream);
639 outputStream.close();
640 this.newFile = file.toString();
641 this.newModel.setModelName(this.newFile.split("-v")[0]);
643 if (this.newFile.contains("-v")) {
644 if (item.getName().endsWith(".zip")) {
645 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
647 } else if (item.getName().endsWith(".yml")) {
648 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
651 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
654 } catch (Exception e) {
655 LOGGER.error("Upload error : ", e);
656 errorMsg = "Upload error:" + e.getMessage();
662 if (!errorMsg.isEmpty()) {
663 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
664 response.setContentType(PolicyUtils.APPLICATION_JSON);
665 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
666 response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
670 List<File> fileList = new ArrayList<>();
671 MsModelUtils modelUtil = new MsModelUtils();
672 this.directory = MODEL;
674 extractFolder(this.newFile);
675 fileList = listModelFiles(this.directory);
677 modelUtil.parseTosca(this.newFile);
679 File file = new File(this.newFile);
685 // Process Main Model file first
686 classMap = new LinkedHashMap<>();
687 for (File file : fileList) {
688 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
689 retrieveDependency(file.toString());
693 modelList = createList();
695 msController.cleanUp(this.newFile);
696 msController.cleanUp(directory);
699 modelList.add(this.newModel.getModelName());
700 String className = this.newModel.getModelName();
701 MsAttributeObject optimizationAttributes = new MsAttributeObject();
702 optimizationAttributes.setClassName(className);
704 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
705 returnAttributeList.put(className, modelUtil.getAttributeString());
706 optimizationAttributes.setAttribute(returnAttributeList);
708 optimizationAttributes.setSubClass(modelUtil.getRetmap());
710 optimizationAttributes.setMatchingSet(modelUtil.getMatchableValues());
712 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
713 returnReferenceList.put(className, modelUtil.getReferenceAttributes());
714 optimizationAttributes.setRefAttribute(returnReferenceList);
716 if (!"".equals(modelUtil.getListConstraints())) {
717 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
718 String[] listArray = modelUtil.getListConstraints().split("#");
719 for (String str : listArray) {
720 String[] strArr = str.split("=");
721 if (strArr.length > 1) {
722 enumList.put(strArr[0], strArr[1]);
725 optimizationAttributes.setEnumType(enumList);
728 classMap = new LinkedHashMap<>();
729 classMap.put(className, optimizationAttributes);
733 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
734 response.setContentType(PolicyUtils.APPLICATION_JSON);
735 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
737 ObjectMapper mapper = new ObjectMapper();
738 JSONObject json = new JSONObject();
739 json.put("classListDatas", modelList);
740 json.put("modelDatas", mapper.writeValueAsString(classMap));
741 json.put("modelType", modelType);
742 json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
744 response.getWriter().write(json.toString());
748 * Unzip file and store in the model directory for processing
750 @SuppressWarnings("rawtypes")
751 private void extractFolder(String zipFile) {
752 File file = new File(zipFile);
754 try (ZipFile zip = new ZipFile(file)) {
755 String newPath = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
756 this.directory = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
757 msController.checkZipDirectory(this.directory);
758 new File(newPath).mkdir();
759 Enumeration zipFileEntries = zip.entries();
761 // Process each entry
762 while (zipFileEntries.hasMoreElements()) {
763 // grab a zip file entry
764 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
765 String currentEntry = entry.getName();
766 File destFile = new File(MODEL + File.separator + currentEntry);
767 File destinationParent = destFile.getParentFile();
769 destinationParent.mkdirs();
771 if (!entry.isDirectory()) {
772 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
774 byte[] data = new byte[BUFFER];
775 try (FileOutputStream fos = new FileOutputStream(destFile);
776 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
777 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
778 dest.write(data, 0, currentByte);
781 } catch (IOException e) {
782 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
784 // PLD should I throw e?
790 if (currentEntry.endsWith(".zip")) {
791 extractFolder(destFile.getAbsolutePath());
794 } catch (IOException e) {
795 LOGGER.error("Failed to unzip model file " + zipFile, e);
799 private void retrieveDependency(String workingFile) {
801 MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
802 Map<String, MsAttributeObject> tempMap;
804 tempMap = utils.processEpackage(workingFile, ModelType.XMI);
806 classMap.putAll(tempMap);
807 LOGGER.info(tempMap);
810 private List<File> listModelFiles(String directoryName) {
811 File fileDirectory = new File(directoryName);
812 List<File> resultList = new ArrayList<>();
813 for (File file : fileDirectory.listFiles()) {
815 resultList.add(file);
816 } else if (file.isDirectory()) {
817 dirDependencyList.add(file.getName());
818 resultList.addAll(listModelFiles(file.getAbsolutePath()));
824 private List<String> createList() {
825 List<String> list = new ArrayList<>();
826 for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
827 if (entrySet.getValue().isPolicyTempalate()) {
828 list.add(entrySet.getKey());
833 if (list.isEmpty()) {
834 if (classMap.containsKey(this.newModel.getModelName())) {
835 list.add(this.newModel.getModelName());
843 public Map<String, String> getAttributesListRefMap() {
844 return attributesListRefMap;
847 public Map<String, LinkedList<String>> getArrayTextList() {
848 return arrayTextList;
851 private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
852 OptimizationObject optimizationObject = new OptimizationObject();
853 optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_OOF));
855 if (policyAdapter.getServiceType() != null) {
856 optimizationObject.setService(policyAdapter.getServiceType());
857 optimizationObject.setVersion(policyAdapter.getVersion());
859 if (policyAdapter.getPolicyName() != null) {
860 optimizationObject.setPolicyName(policyAdapter.getPolicyName());
862 if (policyAdapter.getPolicyDescription() != null) {
863 optimizationObject.setDescription(policyAdapter.getPolicyDescription());
865 if (policyAdapter.getPriority() != null) {
866 optimizationObject.setPriority(policyAdapter.getPriority());
868 optimizationObject.setPriority("9999");
870 if (policyAdapter.getRiskLevel() != null) {
871 optimizationObject.setRiskLevel(policyAdapter.getRiskLevel());
873 if (policyAdapter.getRiskType() != null) {
874 optimizationObject.setRiskType(policyAdapter.getRiskType());
876 if (policyAdapter.getGuard() != null) {
877 optimizationObject.setGuard(policyAdapter.getGuard());
879 return optimizationObject;
885 class OptimizationObject {
887 private String service;
888 private String policyName;
889 private String description;
890 private String templateVersion;
891 private String version;
892 private String priority;
893 private String policyScope;
894 private String riskType;
895 private String riskLevel;
896 private String guard = null;
897 private Object content;