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.io.PrintWriter;
38 import java.util.ArrayList;
39 import java.util.Enumeration;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.LinkedHashMap;
44 import java.util.LinkedList;
45 import java.util.List;
47 import java.util.Map.Entry;
49 import java.util.UUID;
50 import java.util.zip.ZipEntry;
51 import java.util.zip.ZipFile;
53 import javax.servlet.http.HttpServletRequest;
54 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.AttributeDesignatorType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
64 import org.apache.commons.compress.utils.IOUtils;
65 import org.apache.commons.fileupload.FileItem;
66 import org.apache.commons.fileupload.FileUploadException;
67 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
68 import org.apache.commons.fileupload.servlet.ServletFileUpload;
69 import org.apache.commons.lang.StringUtils;
70 import org.json.JSONArray;
71 import org.json.JSONObject;
72 import org.onap.policy.common.logging.flexlogger.FlexLogger;
73 import org.onap.policy.common.logging.flexlogger.Logger;
74 import org.onap.policy.rest.XACMLRestProperties;
75 import org.onap.policy.rest.adapter.PolicyRestAdapter;
76 import org.onap.policy.rest.dao.CommonClassDao;
77 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
78 import org.onap.policy.rest.jpa.OptimizationModels;
79 import org.onap.policy.rest.jpa.PolicyEntity;
80 import org.onap.policy.rest.util.MSAttributeObject;
81 import org.onap.policy.rest.util.MSModelUtils;
82 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
83 import org.onap.portalsdk.core.controller.RestrictedBaseController;
84 import org.springframework.beans.factory.annotation.Autowired;
85 import org.springframework.stereotype.Controller;
86 import org.springframework.web.bind.annotation.RequestMapping;
87 import org.springframework.web.servlet.ModelAndView;
91 public class CreateOptimizationController extends RestrictedBaseController {
92 private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
93 private static CommonClassDao commonClassDao;
95 public static CommonClassDao getCommonClassDao() {
96 return commonClassDao;
99 private OptimizationModels newModel;
100 private String newFile;
101 private String directory;
102 private List<String> modelList = new ArrayList<>();
103 private List<String> dirDependencyList = new ArrayList<>();
104 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
105 String referenceAttributes;
106 String attributeString;
107 Set<String> allManyTrueKeys = new HashSet<>();
109 public static final String DATATYPE = "data_types.policy.data.";
110 public static final String PROPERTIES = ".properties.";
111 public static final String TYPE = ".type";
112 public static final String STRING = "string";
113 public static final String INTEGER = "integer";
114 public static final String LIST = "list";
115 public static final String DEFAULT = ".default";
116 public static final String REQUIRED = ".required";
117 public static final String MATCHABLE = ".matchable";
118 public static final String MANYFALSE = ":MANY-false";
119 public static final String MODEL = "model";
120 public static final String MANY = "MANY-";
121 public static final String UTF8 = "UTF-8";
122 public static final String MODELNAME = "modelName";
123 public static final String APPLICATIONJSON = "application / json";
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();
143 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
144 String jsonContent = null;
146 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
148 String tempJson = root.get("policyJSON").toString();
150 // ---replace empty value with the value below before calling decodeContent method.
151 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
152 LOGGER.info("dummyValue:" + dummyValue);
154 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
155 ObjectMapper mapper = new ObjectMapper();
156 JsonNode tempJsonNode = mapper.readTree(tempJson);
157 jsonContent = msController.decodeContent(tempJsonNode).toString();
158 constructJson(policyData, jsonContent, dummyValue);
159 } catch (Exception e) {
160 LOGGER.error("Error while decoding microservice content", e);
166 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
167 ObjectWriter om = new ObjectMapper().writer();
169 OptimizationObject optimizationObject = setOptimizationObjectValues(policyAdapter);
171 optimizationObject.setContent(jsonContent);
174 json = om.writeValueAsString(optimizationObject);
175 } catch (JsonProcessingException e) {
176 LOGGER.error("Error writing out the object", e);
178 LOGGER.info("input json: " + json);
179 LOGGER.info("input jsonContent: " + jsonContent);
180 String cleanJson = msController.cleanUPJson(json);
182 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
184 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;
192 value = {"/policyController/getOptimizationTemplateData.htm"},
193 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
194 public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
196 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
197 ObjectMapper mapper = new ObjectMapper();
198 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
199 JsonNode root = mapper.readTree(request.getReader());
201 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
202 String servicename = value.toString().split("-v")[0];
203 String version = null;
204 if (value.toString().contains("-v")) {
205 version = value.toString().split("-v")[1];
208 OptimizationModels returnModel = getAttributeObject(servicename, version);
210 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
211 JSONObject jsonHdDefaultObj = null;
212 if (returnHeaderDefauls != null) {
213 jsonHdDefaultObj = new JSONObject();
214 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
215 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
216 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
217 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
218 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
221 String headDefautlsData = "";
222 if (jsonHdDefaultObj != null) {
223 headDefautlsData = jsonHdDefaultObj.toString();
224 LOGGER.info("returnHeaderDefauls headDefautlsData: " + headDefautlsData);
226 headDefautlsData = "null";
229 // Get all keys with "MANY-true" defined in their value from subAttribute
230 Set<String> allkeys = null;
231 if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
232 JSONObject json = new JSONObject(returnModel.getSubattributes());
234 allkeys = allManyTrueKeys;
235 allManyTrueKeys = new HashSet<>();
236 LOGGER.info("allkeys : " + allkeys);
239 // Get element order info
240 String dataOrderInfo = returnModel.getDataOrderInfo();
241 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
242 dataOrderInfo = "\"" + dataOrderInfo + "\"";
245 String nameOfTrueKeys = "";
246 if (allkeys != null) {
247 nameOfTrueKeys = allkeys.toString();
250 String jsonModel = createOptimizationJson(returnModel);
252 JSONObject jsonObject = new JSONObject(jsonModel);
254 JSONObject finalJsonObject = null;
255 if (allkeys != null) {
256 Iterator<String> iter = allkeys.iterator();
257 while (iter.hasNext()) {
258 // Convert to array values for MANY-true keys
259 finalJsonObject = controller.convertToArrayElement(jsonObject, iter.next());
263 if (finalJsonObject != null) {
264 LOGGER.info(finalJsonObject.toString());
265 jsonModel = finalJsonObject.toString();
268 // get all properties with "MANY-true" defined in Ref_attributes
269 Set<String> manyTrueProperties = controller.getManyTrueProperties(returnModel.getRefattributes());
270 JSONObject jsonObj = new JSONObject(jsonModel);
271 for (String s : manyTrueProperties) {
273 // convert to array element for MANY-true properties
274 finalJsonObject = controller.convertToArrayElement(jsonObj, s.trim());
277 if (finalJsonObject != null) {
278 LOGGER.info(finalJsonObject.toString());
279 jsonModel = finalJsonObject.toString();
282 response.setCharacterEncoding(UTF8);
283 response.setContentType(APPLICATIONJSON);
284 request.setCharacterEncoding(UTF8);
285 List<Object> list = new ArrayList<>();
286 PrintWriter out = response.getWriter();
287 String responseString = mapper.writeValueAsString(returnModel);
289 if ("".equals(nameOfTrueKeys)) {
290 j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
291 + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
293 j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
294 + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
295 + headDefautlsData + "}");
298 out.write(list.toString());
302 @SuppressWarnings({"rawtypes", "unchecked"})
303 private String createOptimizationJson(OptimizationModels returnModel) {
304 Map<String, String> attributeMap = new HashMap<>();
305 Map<String, String> refAttributeMap = new HashMap<>();
307 String attribute = returnModel.getAttributes();
308 if (attribute != null) {
309 attribute = attribute.trim();
311 String refAttribute = returnModel.getRefattributes();
312 if (refAttribute != null) {
313 refAttribute = refAttribute.trim();
316 String enumAttribute = returnModel.getEnumValues();
317 if (enumAttribute != null) {
318 enumAttribute = enumAttribute.trim();
321 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
322 if (!StringUtils.isEmpty(attribute)) {
323 attributeMap = controller.convert(attribute, ",");
326 if (!StringUtils.isEmpty(refAttribute)) {
327 refAttributeMap = controller.convert(refAttribute, ",");
330 Gson gson = new Gson();
332 String subAttributes = returnModel.getSubattributes();
333 if (subAttributes != null) {
334 subAttributes = subAttributes.trim();
339 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
341 JSONObject object = new JSONObject();
344 for (Entry<String, String> keySet : attributeMap.entrySet()) {
345 array = new JSONArray();
346 String value = keySet.getValue();
347 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
349 object.put(keySet.getKey().trim(), array);
351 object.put(keySet.getKey().trim(), value.trim());
355 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
356 array = new JSONArray();
357 String value = keySet.getValue().split(":")[0];
358 if (gsonObject.containsKey(value)) {
359 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
360 array.put(recursiveReference(value, gsonObject, enumAttribute));
361 object.put(keySet.getKey().trim(), array);
363 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
366 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
367 array.put(value.trim());
368 object.put(keySet.getKey().trim(), array);
370 object.put(keySet.getKey().trim(), value.trim());
375 return object.toString();
378 @SuppressWarnings("unchecked")
379 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
380 JSONObject object = new JSONObject();
381 Map<String, String> map;
382 Object returnClass = subAttributeMap.get(name);
383 map = (Map<String, String>) returnClass;
386 for (Entry<String, String> m : map.entrySet()) {
387 String[] splitValue = m.getValue().split(":");
388 array = new JSONArray();
389 if (subAttributeMap.containsKey(splitValue[0])) {
390 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
391 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
392 object.put(m.getKey().trim(), array);
394 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
397 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
398 array.put(splitValue[0].trim());
399 object.put(m.getKey().trim(), array);
401 object.put(m.getKey().trim(), splitValue[0].trim());
409 // call this method to start the recursive
410 private Set<String> getAllKeys(JSONObject json) {
411 return getAllKeys(json, new HashSet<>());
414 private Set<String> getAllKeys(JSONArray arr) {
415 return getAllKeys(arr, new HashSet<>());
418 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
419 for (int i = 0; i < arr.length(); i++) {
420 Object obj = arr.get(i);
421 if (obj instanceof JSONObject)
422 keys.addAll(getAllKeys(arr.getJSONObject(i)));
423 if (obj instanceof JSONArray)
424 keys.addAll(getAllKeys(arr.getJSONArray(i)));
430 // this method returns a set of keys with "MANY-true" defined in their value.
431 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
432 for (String key : json.keySet()) {
433 Object obj = json.get(key);
434 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
435 LOGGER.info("key : " + key);
436 LOGGER.info("obj : " + obj);
437 allManyTrueKeys.add(key);
439 if (obj instanceof JSONObject)
440 keys.addAll(getAllKeys(json.getJSONObject(key)));
441 if (obj instanceof JSONArray)
442 keys.addAll(getAllKeys(json.getJSONArray(key)));
449 value = {"/policyController/getModelServiceVersionData.htm"},
450 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
451 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
453 ObjectMapper mapper = new ObjectMapper();
454 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
455 JsonNode root = mapper.readTree(request.getReader());
457 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
458 String servicename = value.split("-v")[0];
459 Set<String> returnList = getVersionList(servicename);
461 response.setCharacterEncoding(UTF8);
462 response.setContentType(APPLICATIONJSON);
463 request.setCharacterEncoding(UTF8);
464 List<Object> list = new ArrayList<>();
465 PrintWriter out = response.getWriter();
466 String responseString = mapper.writeValueAsString(returnList);
467 JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
469 out.write(list.toString());
473 private Set<String> getVersionList(String name) {
474 OptimizationModels workingModel;
475 Set<String> list = new HashSet<>();
476 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
477 for (int i = 0; i < optimizationModelsData.size(); i++) {
478 workingModel = (OptimizationModels) optimizationModelsData.get(i);
479 if (workingModel.getVersion() != null) {
480 list.add(workingModel.getVersion());
488 private OptimizationModels getAttributeObject(String name, String version) {
489 OptimizationModels workingModel = new OptimizationModels();
490 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
491 for (int i = 0; i < optimizationModelsData.size(); i++) {
492 workingModel = (OptimizationModels) optimizationModelsData.get(i);
493 if (version != null) {
494 if (workingModel.getVersion() != null) {
495 if (workingModel.getVersion().equals(version)) {
509 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
510 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, MODELNAME,
514 public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
515 if (policyAdapter.getPolicyData() instanceof PolicyType) {
516 Object policyData = policyAdapter.getPolicyData();
517 PolicyType policy = (PolicyType) policyData;
518 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
519 String policyNameValue =
520 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
521 policyAdapter.setPolicyName(policyNameValue);
522 String description = "";
524 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
525 } catch (Exception e) {
526 LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
527 description = policy.getDescription();
529 policyAdapter.setPolicyDescription(description);
530 // Get the target data under policy.
531 TargetType target = policy.getTarget();
532 if (target != null) {
533 // Under target we have AnyOFType
534 List<AnyOfType> anyOfList = target.getAnyOf();
535 if (anyOfList != null) {
536 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
537 while (iterAnyOf.hasNext()) {
538 AnyOfType anyOf = iterAnyOf.next();
539 // Under AnyOFType we have AllOFType
540 List<AllOfType> allOfList = anyOf.getAllOf();
541 if (allOfList != null) {
542 Iterator<AllOfType> iterAllOf = allOfList.iterator();
543 while (iterAllOf.hasNext()) {
544 AllOfType allOf = iterAllOf.next();
545 // Under AllOFType we have Match
546 List<MatchType> matchList = allOf.getMatch();
547 if (matchList != null) {
548 Iterator<MatchType> iterMatch = matchList.iterator();
549 while (matchList.size() > 1 && iterMatch.hasNext()) {
550 MatchType match = iterMatch.next();
552 // Under the match we have attribute value and
553 // attributeDesignator. So,finally down to the actual attribute.
555 AttributeValueType attributeValue = match.getAttributeValue();
556 String value = (String) attributeValue.getContent().get(0);
557 AttributeDesignatorType designator = match.getAttributeDesignator();
558 String attributeId = designator.getAttributeId();
559 // First match in the target is OnapName, so set that value.
560 if ("ONAPName".equals(attributeId)) {
561 policyAdapter.setOnapName(value);
563 if ("RiskType".equals(attributeId)) {
564 policyAdapter.setRiskType(value);
566 if ("RiskLevel".equals(attributeId)) {
567 policyAdapter.setRiskLevel(value);
569 if ("guard".equals(attributeId)) {
570 policyAdapter.setGuard(value);
572 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
573 PolicyController controller = new PolicyController();
574 String newDate = controller.convertDate(value);
575 policyAdapter.setTtlDate(newDate);
578 readFile(policyAdapter, entity);
588 @SuppressWarnings("unchecked")
589 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
590 String policyScopeName = null;
591 ObjectMapper mapper = new ObjectMapper();
593 OptimizationObject optimizationBody =
594 mapper.readValue(entity.getConfigurationData().getConfigBody(), OptimizationObject.class);
595 policyScopeName = msController.getPolicyScope(optimizationBody.getPolicyScope());
596 policyAdapter.setPolicyScope(policyScopeName);
598 policyAdapter.setPriority(optimizationBody.getPriority());
600 if (optimizationBody.getVersion() != null) {
601 policyAdapter.setServiceType(optimizationBody.getService());
602 policyAdapter.setVersion(optimizationBody.getVersion());
604 policyAdapter.setServiceType(optimizationBody.getService());
606 if (optimizationBody.getContent() != null) {
607 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
608 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) optimizationBody.getContent();
609 msController.readRecursivlyJSONContent(map, data);
610 policyAdapter.setRuleData(data);
613 } catch (Exception e) {
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()) {
664 PrintWriter out = response.getWriter();
666 response.setCharacterEncoding(UTF8);
667 response.setContentType(APPLICATIONJSON);
668 request.setCharacterEncoding(UTF8);
670 JSONObject j = new JSONObject();
671 j.put("errorMsg", errorMsg);
672 out.write(j.toString());
676 List<File> fileList = new ArrayList<>();
677 MSModelUtils modelUtil = new MSModelUtils();
678 this.directory = MODEL;
680 extractFolder(this.newFile);
681 fileList = listModelFiles(this.directory);
683 modelUtil.parseTosca(this.newFile);
685 File file = new File(this.newFile);
691 // Process Main Model file first
692 classMap = new LinkedHashMap<>();
693 for (File file : fileList) {
694 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
695 retrieveDependency(file.toString());
699 modelList = createList();
701 msController.cleanUp(this.newFile);
702 msController.cleanUp(directory);
705 modelList.add(this.newModel.getModelName());
706 String className = this.newModel.getModelName();
707 MSAttributeObject optimizationAttributes = new MSAttributeObject();
708 optimizationAttributes.setClassName(className);
710 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
711 returnAttributeList.put(className, modelUtil.getAttributeString());
712 optimizationAttributes.setAttribute(returnAttributeList);
714 optimizationAttributes.setSubClass(modelUtil.getRetmap());
716 optimizationAttributes.setMatchingSet(modelUtil.getMatchableValues());
718 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
719 returnReferenceList.put(className, modelUtil.getReferenceAttributes());
720 optimizationAttributes.setRefAttribute(returnReferenceList);
722 if (!"".equals(modelUtil.getListConstraints())) {
723 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
724 String[] listArray = modelUtil.getListConstraints().split("#");
725 for (String str : listArray) {
726 String[] strArr = str.split("=");
727 if (strArr.length > 1) {
728 enumList.put(strArr[0], strArr[1]);
731 optimizationAttributes.setEnumType(enumList);
734 classMap = new LinkedHashMap<>();
735 classMap.put(className, optimizationAttributes);
739 PrintWriter out = response.getWriter();
741 response.setCharacterEncoding(UTF8);
742 response.setContentType(APPLICATIONJSON);
743 request.setCharacterEncoding(UTF8);
745 ObjectMapper mapper = new ObjectMapper();
746 JSONObject j = new JSONObject();
747 j.put("classListDatas", modelList);
748 j.put("modelDatas", mapper.writeValueAsString(classMap));
749 j.put("modelType", modelType);
750 j.put("dataOrderInfo", modelUtil.getDataOrderInfo());
752 out.write(j.toString());
756 * Unzip file and store in the model directory for processing
758 @SuppressWarnings("rawtypes")
759 private void extractFolder(String zipFile) {
761 File file = new File(zipFile);
763 try (ZipFile zip = new ZipFile(file)) {
764 String newPath = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
765 this.directory = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
766 msController.checkZipDirectory(this.directory);
767 new File(newPath).mkdir();
768 Enumeration zipFileEntries = zip.entries();
770 // Process each entry
771 while (zipFileEntries.hasMoreElements()) {
772 // grab a zip file entry
773 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
774 String currentEntry = entry.getName();
775 File destFile = new File(MODEL + File.separator + currentEntry);
776 File destinationParent = destFile.getParentFile();
778 destinationParent.mkdirs();
780 if (!entry.isDirectory()) {
781 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
783 byte[] data = new byte[BUFFER];
784 try (FileOutputStream fos = new FileOutputStream(destFile);
785 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
786 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
787 dest.write(data, 0, currentByte);
790 } catch (IOException e) {
791 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
793 // PLD should I throw e?
799 if (currentEntry.endsWith(".zip")) {
800 extractFolder(destFile.getAbsolutePath());
803 } catch (IOException e) {
804 LOGGER.error("Failed to unzip model file " + zipFile, e);
808 private void retrieveDependency(String workingFile) {
810 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
811 Map<String, MSAttributeObject> tempMap;
813 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
815 classMap.putAll(tempMap);
816 LOGGER.info(tempMap);
822 private List<File> listModelFiles(String directoryName) {
823 File fileDirectory = new File(directoryName);
824 List<File> resultList = new ArrayList<>();
825 File[] fList = fileDirectory.listFiles();
826 for (File file : fList) {
828 resultList.add(file);
829 } else if (file.isDirectory()) {
830 dirDependencyList.add(file.getName());
831 resultList.addAll(listModelFiles(file.getAbsolutePath()));
837 private List<String> createList() {
838 List<String> list = new ArrayList<>();
839 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
840 if (cMap.getValue().isPolicyTempalate()) {
841 list.add(cMap.getKey());
846 if (list.isEmpty()) {
847 if (classMap.containsKey(this.newModel.getModelName())) {
848 list.add(this.newModel.getModelName());
856 public Map<String, String> getAttributesListRefMap() {
857 return attributesListRefMap;
860 public Map<String, LinkedList<String>> getArrayTextList() {
861 return arrayTextList;
864 private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
865 OptimizationObject optimizationObject = new OptimizationObject();
866 optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
868 if (policyAdapter.getServiceType() != null) {
869 optimizationObject.setService(policyAdapter.getServiceType());
870 optimizationObject.setVersion(policyAdapter.getVersion());
872 if (policyAdapter.getPolicyName() != null) {
873 optimizationObject.setPolicyName(policyAdapter.getPolicyName());
875 if (policyAdapter.getPolicyDescription() != null) {
876 optimizationObject.setDescription(policyAdapter.getPolicyDescription());
878 if (policyAdapter.getPriority() != null) {
879 optimizationObject.setPriority(policyAdapter.getPriority());
881 optimizationObject.setPriority("9999");
883 if (policyAdapter.getRiskLevel() != null) {
884 optimizationObject.setRiskLevel(policyAdapter.getRiskLevel());
886 if (policyAdapter.getRiskType() != null) {
887 optimizationObject.setRiskType(policyAdapter.getRiskType());
889 if (policyAdapter.getGuard() != null) {
890 optimizationObject.setGuard(policyAdapter.getGuard());
892 return optimizationObject;
897 class OptimizationObject {
899 private String service;
900 private String policyName;
901 private String description;
902 private String templateVersion;
903 private String version;
904 private String priority;
905 private String policyScope;
906 private String riskType;
907 private String riskLevel;
908 private String guard = null;
910 public String getGuard() {
914 public void setGuard(String guard) {
918 public String getRiskType() {
922 public void setRiskType(String riskType) {
923 this.riskType = riskType;
926 public String getRiskLevel() {
930 public void setRiskLevel(String riskLevel) {
931 this.riskLevel = riskLevel;
934 public String getPriority() {
938 public void setPriority(String priority) {
939 this.priority = priority;
942 public String getPolicyScope() {
946 public void setPolicyScope(String policyScope) {
947 this.policyScope = policyScope;
950 public String getVersion() {
954 public void setVersion(String version) {
955 this.version = version;
958 private Object content;
960 public String getPolicyName() {
964 public void setPolicyName(String policyName) {
965 this.policyName = policyName;
968 public String getDescription() {
972 public void setDescription(String description) {
973 this.description = description;
976 public Object getContent() {
980 public void setContent(Object content) {
981 this.content = content;
984 public String getService() {
988 public void setService(String service) {
989 this.service = service;
992 public String getTemplateVersion() {
993 return templateVersion;
996 public void setTemplateVersion(String templateVersion) {
997 this.templateVersion = templateVersion;