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;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
65 import org.apache.commons.compress.utils.IOUtils;
66 import org.apache.commons.fileupload.FileItem;
67 import org.apache.commons.fileupload.FileUploadException;
68 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
69 import org.apache.commons.fileupload.servlet.ServletFileUpload;
70 import org.apache.commons.lang.StringUtils;
71 import org.json.JSONArray;
72 import org.json.JSONObject;
73 import org.onap.policy.common.logging.flexlogger.FlexLogger;
74 import org.onap.policy.common.logging.flexlogger.Logger;
75 import org.onap.policy.rest.XACMLRestProperties;
76 import org.onap.policy.rest.adapter.PolicyRestAdapter;
77 import org.onap.policy.rest.dao.CommonClassDao;
78 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
79 import org.onap.policy.rest.jpa.OptimizationModels;
80 import org.onap.policy.rest.jpa.PolicyEntity;
81 import org.onap.policy.rest.util.MSAttributeObject;
82 import org.onap.policy.rest.util.MSModelUtils;
83 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
84 import org.onap.portalsdk.core.controller.RestrictedBaseController;
85 import org.springframework.beans.factory.annotation.Autowired;
86 import org.springframework.stereotype.Controller;
87 import org.springframework.web.bind.annotation.RequestMapping;
88 import org.springframework.web.servlet.ModelAndView;
92 public class CreateOptimizationController extends RestrictedBaseController {
93 private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
95 private static final int BUFFER = 2048;
97 private static CommonClassDao commonClassDao;
99 public static CommonClassDao getCommonClassDao() {
100 return commonClassDao;
103 private OptimizationModels newModel;
104 private String newFile;
105 private String directory;
106 private List<String> modelList = new ArrayList<>();
107 private List<String> dirDependencyList = new ArrayList<>();
108 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
109 String referenceAttributes;
110 String attributeString;
111 Set<String> allManyTrueKeys = new HashSet<>();
113 public static final String DATATYPE = "data_types.policy.data.";
114 public static final String PROPERTIES = ".properties.";
115 public static final String TYPE = ".type";
116 public static final String STRING = "string";
117 public static final String INTEGER = "integer";
118 public static final String LIST = "list";
119 public static final String DEFAULT = ".default";
120 public static final String REQUIRED = ".required";
121 public static final String MATCHABLE = ".matchable";
122 public static final String MANYFALSE = ":MANY-false";
123 public static final String MODEL = "model";
124 public static final String MANY = "MANY-";
125 public static final String UTF8 = "UTF-8";
126 public static final String MODELNAME = "modelName";
127 public static final String APPLICATIONJSON = "application / json";
130 private CreateOptimizationController(CommonClassDao commonClassDao) {
131 setCommonClassDao(commonClassDao);
134 public static void setCommonClassDao(CommonClassDao commonClassDao) {
135 CreateOptimizationController.commonClassDao = commonClassDao;
138 public CreateOptimizationController() {
142 protected PolicyRestAdapter policyAdapter = null;
143 private Map<String, String> attributesListRefMap = new HashMap<>();
144 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
145 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
147 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
148 String jsonContent = null;
150 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
152 String tempJson = root.get("policyJSON").toString();
154 // ---replace empty value with the value below before calling decodeContent method.
155 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
156 LOGGER.info("dummyValue:" + dummyValue);
158 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
159 ObjectMapper mapper = new ObjectMapper();
160 JsonNode tempJsonNode = mapper.readTree(tempJson);
161 jsonContent = msController.decodeContent(tempJsonNode).toString();
162 constructJson(policyData, jsonContent, dummyValue);
163 } catch (Exception e) {
164 LOGGER.error("Error while decoding microservice content", e);
170 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
171 ObjectWriter om = new ObjectMapper().writer();
173 OptimizationObject optimizationObject = setOptimizationObjectValues(policyAdapter);
175 optimizationObject.setContent(jsonContent);
178 json = om.writeValueAsString(optimizationObject);
179 } catch (JsonProcessingException e) {
180 LOGGER.error("Error writing out the object", e);
182 LOGGER.info("input json: " + json);
183 LOGGER.info("input jsonContent: " + jsonContent);
184 String cleanJson = msController.cleanUpJson(json);
186 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
188 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
189 LOGGER.info("tempJson: " + tempJson);
190 cleanJson = msController.removeNullAttributes(tempJson);
191 policyAdapter.setJsonBody(cleanJson);
192 return policyAdapter;
196 * getOptimizationTemplateData.
198 * @param request HttpServletRequest
199 * @param response HttpServletResponse
200 * @return ModelAndView
201 * @throws IOException IOException
204 value = {"/policyController/getOptimizationTemplateData.htm"},
205 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
206 public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
208 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
209 ObjectMapper mapper = new ObjectMapper();
210 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
211 JsonNode root = mapper.readTree(request.getReader());
213 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
214 String servicename = value.split("-v")[0];
215 String version = null;
216 if (value.contains("-v")) {
217 version = value.split("-v")[1];
220 OptimizationModels returnModel = getAttributeObject(servicename, version);
222 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
223 JSONObject jsonHdDefaultObj = null;
224 if (returnHeaderDefauls != null) {
225 jsonHdDefaultObj = new JSONObject();
226 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
227 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
228 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
229 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
230 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
233 String headDefautlsData = "";
234 if (jsonHdDefaultObj != null) {
235 headDefautlsData = jsonHdDefaultObj.toString();
236 LOGGER.info("returnHeaderDefauls headDefautlsData: " + headDefautlsData);
238 headDefautlsData = "null";
241 // Get all keys with "MANY-true" defined in their value from subAttribute
242 Set<String> allkeys = null;
243 if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
244 getAllKeys(new JSONObject(returnModel.getSubattributes()));
245 allkeys = allManyTrueKeys;
246 allManyTrueKeys = new HashSet<>();
247 LOGGER.info("allkeys : " + allkeys);
250 // Get element order info
251 String dataOrderInfo = returnModel.getDataOrderInfo();
252 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
253 dataOrderInfo = "\"" + dataOrderInfo + "\"";
256 String nameOfTrueKeys = "";
257 if (allkeys != null) {
258 nameOfTrueKeys = allkeys.toString();
261 String jsonModel = createOptimizationJson(returnModel);
263 JSONObject jsonObject = new JSONObject(jsonModel);
265 JSONObject finalJsonObject = null;
266 if (allkeys != null) {
267 Iterator<String> iter = allkeys.iterator();
268 while (iter.hasNext()) {
269 // Convert to array values for MANY-true keys
270 finalJsonObject = controller.convertToArrayElement(jsonObject, iter.next());
274 if (finalJsonObject != null) {
275 LOGGER.info(finalJsonObject.toString());
276 jsonModel = finalJsonObject.toString();
279 // get all properties with "MANY-true" defined in Ref_attributes
280 Set<String> manyTrueProperties = controller.getManyTrueProperties(returnModel.getRefattributes());
281 JSONObject jsonObj = new JSONObject(jsonModel);
282 for (String s : manyTrueProperties) {
284 // convert to array element for MANY-true properties
285 finalJsonObject = controller.convertToArrayElement(jsonObj, s.trim());
288 if (finalJsonObject != null) {
289 LOGGER.info(finalJsonObject.toString());
290 jsonModel = finalJsonObject.toString();
293 response.setCharacterEncoding(UTF8);
294 response.setContentType(APPLICATIONJSON);
295 request.setCharacterEncoding(UTF8);
296 List<Object> list = new ArrayList<>();
297 String responseString = mapper.writeValueAsString(returnModel);
298 JSONObject json = null;
299 if ("".equals(nameOfTrueKeys)) {
300 json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
301 + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
303 json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
304 + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
305 + headDefautlsData + "}");
308 response.getWriter().write(list.toString());
312 @SuppressWarnings({"rawtypes", "unchecked"})
313 private String createOptimizationJson(OptimizationModels returnModel) {
314 Map<String, String> attributeMap = new HashMap<>();
315 Map<String, String> refAttributeMap = new HashMap<>();
317 String attribute = returnModel.getAttributes();
318 if (attribute != null) {
319 attribute = attribute.trim();
321 String refAttribute = returnModel.getRefattributes();
322 if (refAttribute != null) {
323 refAttribute = refAttribute.trim();
326 String enumAttribute = returnModel.getEnumValues();
327 if (enumAttribute != null) {
328 enumAttribute = enumAttribute.trim();
331 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
332 if (!StringUtils.isEmpty(attribute)) {
333 attributeMap = controller.convert(attribute, ",");
336 if (!StringUtils.isEmpty(refAttribute)) {
337 refAttributeMap = controller.convert(refAttribute, ",");
340 Gson gson = new Gson();
342 String subAttributes = returnModel.getSubattributes();
343 if (subAttributes != null) {
344 subAttributes = subAttributes.trim();
349 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
351 JSONObject object = new JSONObject();
354 for (Entry<String, String> keySet : attributeMap.entrySet()) {
355 array = new JSONArray();
356 String value = keySet.getValue();
357 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
359 object.put(keySet.getKey().trim(), array);
361 object.put(keySet.getKey().trim(), value.trim());
365 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
366 array = new JSONArray();
367 String value = keySet.getValue().split(":")[0];
368 if (gsonObject.containsKey(value)) {
369 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
370 array.put(recursiveReference(value, gsonObject, enumAttribute));
371 object.put(keySet.getKey().trim(), array);
373 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
376 if ("true".equalsIgnoreCase(keySet.getValue().split(MANY)[1])) {
377 array.put(value.trim());
378 object.put(keySet.getKey().trim(), array);
380 object.put(keySet.getKey().trim(), value.trim());
385 return object.toString();
388 @SuppressWarnings("unchecked")
389 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
390 JSONObject object = new JSONObject();
391 Map<String, String> map;
392 Object returnClass = subAttributeMap.get(name);
393 map = (Map<String, String>) returnClass;
396 for (Entry<String, String> m : map.entrySet()) {
397 String[] splitValue = m.getValue().split(":");
398 array = new JSONArray();
399 if (subAttributeMap.containsKey(splitValue[0])) {
400 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
401 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
402 object.put(m.getKey().trim(), array);
404 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
407 if ("true".equalsIgnoreCase(m.getValue().split(MANY)[1])) {
408 array.put(splitValue[0].trim());
409 object.put(m.getKey().trim(), array);
411 object.put(m.getKey().trim(), splitValue[0].trim());
419 // call this method to start the recursive
420 private Set<String> getAllKeys(JSONObject json) {
421 return getAllKeys(json, new HashSet<>());
424 private Set<String> getAllKeys(JSONArray arr) {
425 return getAllKeys(arr, new HashSet<>());
428 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
429 for (int i = 0; i < arr.length(); i++) {
430 Object obj = arr.get(i);
431 if (obj instanceof JSONObject) {
432 keys.addAll(getAllKeys(arr.getJSONObject(i)));
434 if (obj instanceof JSONArray) {
435 keys.addAll(getAllKeys(arr.getJSONArray(i)));
442 // this method returns a set of keys with "MANY-true" defined in their value.
443 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
444 for (String key : json.keySet()) {
445 Object obj = json.get(key);
446 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
447 LOGGER.info("key : " + key);
448 LOGGER.info("obj : " + obj);
449 allManyTrueKeys.add(key);
451 if (obj instanceof JSONObject) {
452 keys.addAll(getAllKeys(json.getJSONObject(key)));
454 if (obj instanceof JSONArray) {
455 keys.addAll(getAllKeys(json.getJSONArray(key)));
463 * getModelServiceVersionData.
465 * @param request HttpServletRequest
466 * @param response HttpServletResponse
467 * @return ModelAndView
468 * @throws IOException IOException
471 value = {"/policyController/getModelServiceVersionData.htm"},
472 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
473 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
475 ObjectMapper mapper = new ObjectMapper();
476 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
477 JsonNode root = mapper.readTree(request.getReader());
479 final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
480 final String servicename = value.split("-v")[0];
482 response.setCharacterEncoding(UTF8);
483 response.setContentType(APPLICATIONJSON);
484 request.setCharacterEncoding(UTF8);
485 List<Object> list = new ArrayList<>();
486 list.add(new JSONObject("{optimizationModelVersionData: "
487 + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
488 response.getWriter().write(list.toString());
492 private Set<String> getVersionList(String name) {
493 OptimizationModels workingModel;
494 Set<String> list = new HashSet<>();
495 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
496 for (int i = 0; i < optimizationModelsData.size(); i++) {
497 workingModel = (OptimizationModels) optimizationModelsData.get(i);
498 if (workingModel.getVersion() != null) {
499 list.add(workingModel.getVersion());
507 private OptimizationModels getAttributeObject(String name, String version) {
508 OptimizationModels workingModel = new OptimizationModels();
509 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, MODELNAME, name);
510 for (int i = 0; i < optimizationModelsData.size(); i++) {
511 workingModel = (OptimizationModels) optimizationModelsData.get(i);
512 if (version != null) {
513 if (workingModel.getVersion() != null) {
514 if (workingModel.getVersion().equals(version)) {
528 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
529 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, MODELNAME,
534 * prePopulatePolicyData.
536 * @param policyAdapter PolicyRestAdapter
537 * @param entity PolicyEntity
539 public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
540 if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
543 Object policyData = policyAdapter.getPolicyData();
544 PolicyType policy = (PolicyType) policyData;
545 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
546 String policyNameValue =
547 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
548 policyAdapter.setPolicyName(policyNameValue);
549 String description = "";
551 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
552 } catch (Exception e) {
553 LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
554 description = policy.getDescription();
556 policyAdapter.setPolicyDescription(description);
557 // Get the target data under policy.
558 TargetType target = policy.getTarget();
559 if (target == null) {
562 // Under target we have AnyOFType
563 List<AnyOfType> anyOfList = target.getAnyOf();
564 if (anyOfList == null) {
567 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
568 while (iterAnyOf.hasNext()) {
569 AnyOfType anyOf = iterAnyOf.next();
570 // Under AnyOFType we have AllOFType
571 List<AllOfType> allOfList = anyOf.getAllOf();
572 if (allOfList == null) {
575 Iterator<AllOfType> iterAllOf = allOfList.iterator();
576 while (iterAllOf.hasNext()) {
577 AllOfType allOf = iterAllOf.next();
578 // Under AllOFType we have Match
579 List<MatchType> matchList = allOf.getMatch();
580 if (matchList == null) {
583 Iterator<MatchType> iterMatch = matchList.iterator();
584 while (matchList.size() > 1 && iterMatch.hasNext()) {
585 MatchType match = iterMatch.next();
587 // Under the match we have attribute value and
588 // attributeDesignator. So,finally down to the actual attribute.
590 AttributeValueType attributeValue = match.getAttributeValue();
591 String value = (String) attributeValue.getContent().get(0);
592 AttributeDesignatorType designator = match.getAttributeDesignator();
593 String attributeId = designator.getAttributeId();
594 // First match in the target is OnapName, so set that value.
595 if ("ONAPName".equals(attributeId)) {
596 policyAdapter.setOnapName(value);
598 if ("RiskType".equals(attributeId)) {
599 policyAdapter.setRiskType(value);
601 if ("RiskLevel".equals(attributeId)) {
602 policyAdapter.setRiskLevel(value);
604 if ("guard".equals(attributeId)) {
605 policyAdapter.setGuard(value);
607 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
608 PolicyController controller = new PolicyController();
609 String newDate = controller.convertDate(value);
610 policyAdapter.setTtlDate(newDate);
613 readFile(policyAdapter, entity);
618 @SuppressWarnings("unchecked")
619 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
620 String policyScopeName = null;
621 ObjectMapper mapper = new ObjectMapper();
623 OptimizationObject optimizationBody =
624 mapper.readValue(entity.getConfigurationData().getConfigBody(), OptimizationObject.class);
625 policyScopeName = msController.getPolicyScope(optimizationBody.getPolicyScope());
626 policyAdapter.setPolicyScope(policyScopeName);
628 policyAdapter.setPriority(optimizationBody.getPriority());
630 if (optimizationBody.getVersion() != null) {
631 policyAdapter.setServiceType(optimizationBody.getService());
632 policyAdapter.setVersion(optimizationBody.getVersion());
634 policyAdapter.setServiceType(optimizationBody.getService());
636 if (optimizationBody.getContent() != null) {
637 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
638 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) optimizationBody.getContent();
639 msController.readRecursivlyJSONContent(map, data);
640 policyAdapter.setRuleData(data);
643 } catch (Exception e) {
652 * @param request HttpServletRequest
653 * @param response HttpServletResponse
654 * @throws IOException IOException
655 * @throws FileUploadException FileUploadException
658 value = {"/oof_dictionary/set_ModelData"},
659 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
660 public void setModelData(HttpServletRequest request, HttpServletResponse response)
661 throws IOException, FileUploadException {
662 modelList = new ArrayList<>();
663 dirDependencyList = new ArrayList<>();
664 classMap = new LinkedHashMap<>();
665 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
669 String errorMsg = "";
670 for (FileItem item : items) {
671 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
672 this.newModel = new OptimizationModels();
674 File file = new File(item.getName());
675 OutputStream outputStream = new FileOutputStream(file);
676 IOUtils.copy(item.getInputStream(), outputStream);
677 outputStream.close();
678 this.newFile = file.toString();
679 this.newModel.setModelName(this.newFile.split("-v")[0]);
681 if (this.newFile.contains("-v")) {
682 if (item.getName().endsWith(".zip")) {
683 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
685 } else if (item.getName().endsWith(".yml")) {
686 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
689 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
692 } catch (Exception e) {
693 LOGGER.error("Upload error : ", e);
694 errorMsg = "Upload error:" + e.getMessage();
700 if (!errorMsg.isEmpty()) {
701 response.setCharacterEncoding(UTF8);
702 response.setContentType(APPLICATIONJSON);
703 request.setCharacterEncoding(UTF8);
704 response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
708 List<File> fileList = new ArrayList<>();
709 MSModelUtils modelUtil = new MSModelUtils();
710 this.directory = MODEL;
712 extractFolder(this.newFile);
713 fileList = listModelFiles(this.directory);
715 modelUtil.parseTosca(this.newFile);
717 File file = new File(this.newFile);
723 // Process Main Model file first
724 classMap = new LinkedHashMap<>();
725 for (File file : fileList) {
726 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
727 retrieveDependency(file.toString());
731 modelList = createList();
733 msController.cleanUp(this.newFile);
734 msController.cleanUp(directory);
737 modelList.add(this.newModel.getModelName());
738 String className = this.newModel.getModelName();
739 MSAttributeObject optimizationAttributes = new MSAttributeObject();
740 optimizationAttributes.setClassName(className);
742 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
743 returnAttributeList.put(className, modelUtil.getAttributeString());
744 optimizationAttributes.setAttribute(returnAttributeList);
746 optimizationAttributes.setSubClass(modelUtil.getRetmap());
748 optimizationAttributes.setMatchingSet(modelUtil.getMatchableValues());
750 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
751 returnReferenceList.put(className, modelUtil.getReferenceAttributes());
752 optimizationAttributes.setRefAttribute(returnReferenceList);
754 if (!"".equals(modelUtil.getListConstraints())) {
755 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
756 String[] listArray = modelUtil.getListConstraints().split("#");
757 for (String str : listArray) {
758 String[] strArr = str.split("=");
759 if (strArr.length > 1) {
760 enumList.put(strArr[0], strArr[1]);
763 optimizationAttributes.setEnumType(enumList);
766 classMap = new LinkedHashMap<>();
767 classMap.put(className, optimizationAttributes);
771 response.setCharacterEncoding(UTF8);
772 response.setContentType(APPLICATIONJSON);
773 request.setCharacterEncoding(UTF8);
775 ObjectMapper mapper = new ObjectMapper();
776 JSONObject json = new JSONObject();
777 json.put("classListDatas", modelList);
778 json.put("modelDatas", mapper.writeValueAsString(classMap));
779 json.put("modelType", modelType);
780 json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
782 response.getWriter().write(json.toString());
786 * Unzip file and store in the model directory for processing
788 @SuppressWarnings("rawtypes")
789 private void extractFolder(String zipFile) {
790 File file = new File(zipFile);
792 try (ZipFile zip = new ZipFile(file)) {
793 String newPath = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
794 this.directory = MODEL + File.separator + zipFile.substring(0, zipFile.length() - 4);
795 msController.checkZipDirectory(this.directory);
796 new File(newPath).mkdir();
797 Enumeration zipFileEntries = zip.entries();
799 // Process each entry
800 while (zipFileEntries.hasMoreElements()) {
801 // grab a zip file entry
802 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
803 String currentEntry = entry.getName();
804 File destFile = new File(MODEL + File.separator + currentEntry);
805 File destinationParent = destFile.getParentFile();
807 destinationParent.mkdirs();
809 if (!entry.isDirectory()) {
810 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
812 byte[] data = new byte[BUFFER];
813 try (FileOutputStream fos = new FileOutputStream(destFile);
814 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
815 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
816 dest.write(data, 0, currentByte);
819 } catch (IOException e) {
820 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
822 // PLD should I throw e?
828 if (currentEntry.endsWith(".zip")) {
829 extractFolder(destFile.getAbsolutePath());
832 } catch (IOException e) {
833 LOGGER.error("Failed to unzip model file " + zipFile, e);
837 private void retrieveDependency(String workingFile) {
839 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
840 Map<String, MSAttributeObject> tempMap;
842 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
844 classMap.putAll(tempMap);
845 LOGGER.info(tempMap);
851 private List<File> listModelFiles(String directoryName) {
852 File fileDirectory = new File(directoryName);
853 List<File> resultList = new ArrayList<>();
854 for (File file : fileDirectory.listFiles()) {
856 resultList.add(file);
857 } else if (file.isDirectory()) {
858 dirDependencyList.add(file.getName());
859 resultList.addAll(listModelFiles(file.getAbsolutePath()));
865 private List<String> createList() {
866 List<String> list = new ArrayList<>();
867 for (Entry<String, MSAttributeObject> entrySet : classMap.entrySet()) {
868 if (entrySet.getValue().isPolicyTempalate()) {
869 list.add(entrySet.getKey());
874 if (list.isEmpty()) {
875 if (classMap.containsKey(this.newModel.getModelName())) {
876 list.add(this.newModel.getModelName());
884 public Map<String, String> getAttributesListRefMap() {
885 return attributesListRefMap;
888 public Map<String, LinkedList<String>> getArrayTextList() {
889 return arrayTextList;
892 private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
893 OptimizationObject optimizationObject = new OptimizationObject();
894 optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
896 if (policyAdapter.getServiceType() != null) {
897 optimizationObject.setService(policyAdapter.getServiceType());
898 optimizationObject.setVersion(policyAdapter.getVersion());
900 if (policyAdapter.getPolicyName() != null) {
901 optimizationObject.setPolicyName(policyAdapter.getPolicyName());
903 if (policyAdapter.getPolicyDescription() != null) {
904 optimizationObject.setDescription(policyAdapter.getPolicyDescription());
906 if (policyAdapter.getPriority() != null) {
907 optimizationObject.setPriority(policyAdapter.getPriority());
909 optimizationObject.setPriority("9999");
911 if (policyAdapter.getRiskLevel() != null) {
912 optimizationObject.setRiskLevel(policyAdapter.getRiskLevel());
914 if (policyAdapter.getRiskType() != null) {
915 optimizationObject.setRiskType(policyAdapter.getRiskType());
917 if (policyAdapter.getGuard() != null) {
918 optimizationObject.setGuard(policyAdapter.getGuard());
920 return optimizationObject;
926 class OptimizationObject {
928 private String service;
929 private String policyName;
930 private String description;
931 private String templateVersion;
932 private String version;
933 private String priority;
934 private String policyScope;
935 private String riskType;
936 private String riskLevel;
937 private String guard = null;
938 private Object content;