2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-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;
24 import com.att.research.xacml.util.XACMLProperties;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.DeserializationFeature;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.ObjectWriter;
30 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
31 import com.fasterxml.jackson.databind.node.ObjectNode;
32 import com.google.gson.Gson;
33 import java.io.BufferedInputStream;
34 import java.io.BufferedOutputStream;
36 import java.io.FileOutputStream;
37 import java.io.IOException;
38 import java.io.OutputStream;
39 import java.io.PrintWriter;
40 import java.io.StringReader;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.LinkedHashMap;
50 import java.util.LinkedList;
51 import java.util.List;
53 import java.util.Map.Entry;
55 import java.util.TreeMap;
56 import java.util.UUID;
57 import java.util.zip.ZipEntry;
58 import java.util.zip.ZipFile;
59 import javax.json.Json;
60 import javax.json.JsonArray;
61 import javax.json.JsonArrayBuilder;
62 import javax.json.JsonObject;
63 import javax.json.JsonObjectBuilder;
64 import javax.json.JsonReader;
65 import javax.json.JsonValue;
66 import javax.servlet.http.HttpServletRequest;
67 import javax.servlet.http.HttpServletResponse;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
75 import org.apache.commons.compress.utils.IOUtils;
76 import org.apache.commons.fileupload.FileItem;
77 import org.apache.commons.fileupload.FileUploadException;
78 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
79 import org.apache.commons.fileupload.servlet.ServletFileUpload;
80 import org.apache.commons.io.FileUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.json.JSONArray;
83 import org.json.JSONObject;
84 import org.onap.policy.common.logging.flexlogger.FlexLogger;
85 import org.onap.policy.common.logging.flexlogger.Logger;
86 import org.onap.policy.rest.XACMLRestProperties;
87 import org.onap.policy.rest.adapter.PolicyRestAdapter;
88 import org.onap.policy.rest.dao.CommonClassDao;
89 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
90 import org.onap.policy.rest.jpa.MicroServiceModels;
91 import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
92 import org.onap.policy.rest.jpa.PolicyEntity;
93 import org.onap.policy.rest.util.MSAttributeObject;
94 import org.onap.policy.rest.util.MSModelUtils;
95 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
96 import org.onap.portalsdk.core.controller.RestrictedBaseController;
97 import org.onap.portalsdk.core.web.support.JsonMessage;
98 import org.springframework.beans.factory.annotation.Autowired;
99 import org.springframework.http.MediaType;
100 import org.springframework.stereotype.Controller;
101 import org.springframework.web.bind.annotation.RequestMapping;
102 import org.springframework.web.servlet.ModelAndView;
106 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
107 private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
109 private static CommonClassDao commonClassDao;
111 public static CommonClassDao getCommonClassDao() {
112 return commonClassDao;
115 public static void setCommonClassDao(CommonClassDao commonClassDao) {
116 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
119 private MicroServiceModels newModel;
120 private String newFile;
121 private String directory;
122 private List<String> modelList = new ArrayList<>();
123 private List<String> dirDependencyList = new ArrayList<>();
124 private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
125 String referenceAttributes;
126 String attributeString;
127 Set<String> allManyTrueKeys = new HashSet<>();
129 public static final String DATATYPE = "data_types.policy.data.";
130 public static final String PROPERTIES = ".properties.";
131 public static final String TYPE = ".type";
132 public static final String STRING = "string";
133 public static final String INTEGER = "integer";
134 public static final String LIST = "list";
135 public static final String DEFAULT = ".default";
136 public static final String REQUIRED = ".required";
137 public static final String MATCHABLE = ".matchable";
138 public static final String MANYFALSE = ":MANY-false";
142 private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
143 CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
146 public CreateDcaeMicroServiceController() {
150 protected PolicyRestAdapter policyAdapter = null;
151 private int priorityCount;
152 private Map<String, String> attributesListRefMap = new HashMap<>();
153 private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
154 private Map<String, String> jsonStringValues = new HashMap<>();
156 public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
158 String jsonContent = null;
160 LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
162 String tempJson = root.get("policyJSON").toString();
163 JSONObject policyJSON = new JSONObject(root.get("policyJSON").toString());
164 if (policyJSON != null) {
165 saveOriginalJsonObject(policyJSON, jsonStringValues);
167 // ---replace empty value with the value below before calling decodeContent method.
168 String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
169 LOGGER.info("dummyValue:" + dummyValue);
171 StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
172 ObjectMapper mapper = new ObjectMapper();
173 JsonNode tempJsonNode = mapper.readTree(tempJson);
174 jsonContent = decodeContent(tempJsonNode).toString();
175 constructJson(policyData, jsonContent, dummyValue);
176 } catch (Exception e) {
177 LOGGER.error("Error while decoding microservice content", e);
180 // ----Here is the final step to reset the original value back.
181 if(policyData.getJsonBody() != null && jsonStringValues.size() > 0){
182 String contentBody = policyData.getJsonBody();
183 JSONObject contentJson= new JSONObject(contentBody);
184 JSONObject content = contentJson.getJSONObject("content");
185 content = setOriginalJsonObject(content, jsonStringValues);
186 contentJson.put("content", content);
187 policyData.setJsonBody(contentJson.toString());
194 * To save the original JSON string from the root.
196 * @param jsonObj holds the value from the root.
197 * @param jsonStringValues value get saved.
199 private void saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
200 for (Object key : jsonObj.keySet()) {
201 String keyStr = (String) key;
202 Object keyvalue = jsonObj.get(keyStr);
203 if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
204 jsonStringValues.put(keyStr, keyvalue.toString());
207 // for nested objects iteration if required
208 if (keyvalue instanceof JSONObject) {
209 saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
215 * To reset the original JSON string back associated to its key.
217 * @param jsonObj holds the original json.
218 * @param jsonStringValues value to be reset.
221 private JSONObject setOriginalJsonObject(JSONObject jsonObj , Map<String, String> jsonStringValues) {
222 for (Object key : jsonObj.keySet()) {
223 String keyStr = (String)key;
224 Object keyvalue = jsonObj.get(keyStr);
225 String originalValue = getOriginalValue(keyStr);
226 if (originalValue != null) {
227 jsonObj.put(keyStr, originalValue);
230 //for nested objects iteration if required
231 if (keyvalue instanceof JSONObject) {
232 setOriginalJsonObject((JSONObject)keyvalue, jsonStringValues);
233 jsonObj.put(keyStr, originalValue);
236 if (keyvalue instanceof JSONArray) {
237 for (int i = 0; i < ((JSONArray)keyvalue).length(); i++) {
238 JSONObject temp = ((JSONArray)keyvalue).getJSONObject(i);
239 setOriginalJsonObject(temp, jsonStringValues);
247 private GroupPolicyScopeList getPolicyObject(String policyScope) {
248 return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
251 private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
252 ObjectWriter om = new ObjectMapper().writer();
254 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
255 MicroServiceModels returnModel = new MicroServiceModels();
256 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
257 if (policyAdapter.getServiceType() != null) {
258 microServiceObject.setService(policyAdapter.getServiceType());
259 microServiceObject.setVersion(policyAdapter.getVersion());
260 returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
262 if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
263 if (policyAdapter.getUuid() != null) {
264 microServiceObject.setUuid(policyAdapter.getUuid());
266 if (policyAdapter.getLocation() != null) {
267 microServiceObject.setLocation(policyAdapter.getLocation());
269 if (policyAdapter.getConfigName() != null) {
270 microServiceObject.setConfigName(policyAdapter.getConfigName());
272 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
273 if (policyScopeValue != null) {
274 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
278 if (policyAdapter.getPolicyName() != null) {
279 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
281 if (policyAdapter.getPolicyDescription() != null) {
282 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
284 if (policyAdapter.getPriority() != null) {
285 microServiceObject.setPriority(policyAdapter.getPriority());
287 microServiceObject.setPriority("9999");
290 if (policyAdapter.getRiskLevel() != null) {
291 microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
293 if (policyAdapter.getRiskType() != null) {
294 microServiceObject.setRiskType(policyAdapter.getRiskType());
296 if (policyAdapter.getGuard() != null) {
297 microServiceObject.setGuard(policyAdapter.getGuard());
299 microServiceObject.setContent(jsonContent);
302 json = om.writeValueAsString(microServiceObject);
303 } catch (JsonProcessingException e) {
304 LOGGER.error("Error writing out the object", e);
306 LOGGER.info("input json: " + json);
307 LOGGER.info("input jsonContent: " + jsonContent);
308 String cleanJson = cleanUPJson(json);
309 // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
311 StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
312 LOGGER.info("tempJson: " + tempJson);
313 cleanJson = removeNullAttributes(tempJson);
314 policyAdapter.setJsonBody(cleanJson);
315 return policyAdapter;
318 public String removeNullAttributes(String cleanJson) {
319 ObjectMapper mapper = new ObjectMapper();
322 JsonNode rootNode = mapper.readTree(cleanJson);
323 JsonNode returnNode = mapper.readTree(cleanJson);
324 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
325 boolean remove = false;
326 JsonObject removed = null;
327 boolean contentChanged = false;
328 while (fieldsIterator.hasNext()) {
329 Map.Entry<String, JsonNode> field = fieldsIterator.next();
330 final String key = field.getKey();
331 final JsonNode value = field.getValue();
332 if ("content".equalsIgnoreCase(key)) {
333 String contentStr = value.toString();
334 try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
335 JsonObject jsonContent = reader.readObject();
336 removed = removeNull(jsonContent);
337 if (!jsonContent.toString().equals(removed.toString())) {
338 contentChanged = true;
342 if (value == null || value.isNull()) {
343 ((ObjectNode) returnNode).remove(key);
348 cleanJson = returnNode.toString();
350 if (value == null || value.isNull()) {
351 ((ObjectNode) returnNode).remove(key);
356 cleanJson = returnNode.toString();
359 if (contentChanged) {
360 // set modified content to cleanJson
361 JSONObject jObject = new JSONObject(cleanJson);
362 jObject.put("content", removed.toString());
363 cleanJson = cleanUPJson(jObject.toString());
366 } catch (IOException e) {
367 LOGGER.error("Error writing out the JsonNode", e);
373 * To verify if it is a JSON string. If it is, then return its original value.
375 * @param key holds the values
378 private String getOriginalValue(String key) {
379 for (String k : jsonStringValues.keySet()) {
380 if (k.contains("@")) {
381 String[] arrOfKeys = k.split("@");
382 for (int i = 0; i < arrOfKeys.length; i++) {
383 if (arrOfKeys[i].contains(".")) {
384 arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
385 if (arrOfKeys[i].equals(key)) {
386 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
387 new String[] {"\\\""});
392 if (k.endsWith(key)) {
393 return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
400 public JsonArray removeNull(JsonArray array) {
401 JsonArrayBuilder builder = Json.createArrayBuilder();
403 for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
404 JsonValue value = it.next();
405 switch (value.getValueType()) {
407 JsonArray a = removeNull(array.getJsonArray(i));
412 JsonObject object = removeNull(array.getJsonObject(i));
413 if (!object.isEmpty())
417 String s = array.getString(i);
418 if (s != null && !s.isEmpty())
422 builder.add(array.getJsonNumber(i));
426 builder.add(array.getBoolean(i));
432 return builder.build();
435 public JsonObject removeNull(JsonObject obj) {
436 JsonObjectBuilder builder = Json.createObjectBuilder();
437 for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
438 Entry<String, JsonValue> e = it.next();
439 String key = e.getKey();
440 JsonValue value = e.getValue();
441 switch (value.getValueType()) {
443 JsonArray array = removeNull(obj.getJsonArray(key));
444 if (!array.isEmpty())
445 builder.add(key, array);
448 JsonObject object = removeNull(obj.getJsonObject(key));
449 if (!object.isEmpty()) {
450 if (!jsonStringValues.isEmpty()) {
451 String originalValue = getOriginalValue(key);
452 if (originalValue != null) {
453 builder.add(key, object.toString());
457 builder.add(key, object);
461 String s = obj.getString(key);
462 if (s != null && !s.isEmpty()) {
463 if (!jsonStringValues.isEmpty()) {
464 String originalValue = getOriginalValue(key);
465 if (originalValue != null) {
466 s = getOriginalValue(key);
473 builder.add(key, obj.getJsonNumber(key));
477 builder.add(key, obj.getBoolean(key));
483 return builder.build();
486 public String cleanUPJson(String json) {
487 String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
488 new String[] {"\\", "\\", "\\"});
489 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
491 StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
493 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
494 new String[] {"\"", "\"", "[{", "}]"});
495 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"});
496 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
497 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, new String[] {"{", "}"});
498 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\"\"", "\"\""}, new String[] {"\"", "\""});
499 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\""}, new String[] {""});
500 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\""}, new String[] {"\""});
501 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\\\\\\"}, new String[] {"\""});
502 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\\""}, new String[] {"\""});
503 cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
507 public JSONObject decodeContent(JsonNode jsonNode) {
508 Iterator<JsonNode> jsonElements = jsonNode.elements();
509 Iterator<String> jsonKeys = jsonNode.fieldNames();
510 Map<String, String> element = new TreeMap<>();
511 while (jsonElements.hasNext() && jsonKeys.hasNext()) {
512 element.put(jsonKeys.next(), jsonElements.next().toString());
514 JSONObject jsonResult = new JSONObject();
515 JSONArray jsonArray = null;
516 String oldValue = null;
517 String nodeKey = null;
518 String arryKey = null;
519 Boolean isArray = false;
520 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
521 ObjectNode node = nodeFactory.objectNode();
522 String prevKey = null;
524 for (Entry<String, String> entry : element.entrySet()) {
525 String key = entry.getKey();
526 String value = entry.getValue();
527 if (key.contains(".")) {
528 presKey = key.substring(0, key.indexOf('.'));
529 } else if (key.contains("@")) {
530 presKey = key.substring(0, key.indexOf('@'));
534 // first check if we are different from old.
535 LOGGER.info(key + "\n");
536 if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
537 && oldValue != null) {
538 if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
539 jsonResult.put(oldValue, jsonArray);
540 jsonArray = new JSONArray();
542 } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
543 jsonResult.put(oldValue, jsonArray);
545 jsonArray = new JSONArray();
550 if (key.contains(".")) {
551 if (nodeKey == null) {
552 nodeKey = key.substring(0, key.indexOf('.'));
554 if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
555 node.put(key.substring(key.indexOf('.') + 1), value);
557 if (node.size() != 0) {
558 if (nodeKey.contains("@")) {
559 if (arryKey == null) {
560 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
562 if (nodeKey.endsWith("@0")) {
564 jsonArray = new JSONArray();
566 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
567 jsonArray.put(decodeContent(node));
569 if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
570 || !key.contains("@")) {
571 jsonResult.put(arryKey, jsonArray);
572 jsonArray = new JSONArray();
574 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
577 jsonResult.put(nodeKey, decodeContent(node));
579 node = nodeFactory.objectNode();
581 nodeKey = key.substring(0, key.indexOf('.'));
582 if (nodeKey.contains("@")) {
583 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
585 node.put(key.substring(key.indexOf('.') + 1), value);
588 if (node.size() != 0) {
589 if (nodeKey.contains("@")) {
590 if (arryKey == null) {
591 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
593 if (nodeKey.endsWith("@0")) {
595 jsonArray = new JSONArray();
597 if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
598 jsonArray.put(decodeContent(node));
600 jsonResult.put(arryKey, jsonArray);
601 jsonArray = new JSONArray();
602 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
605 jsonResult.put(nodeKey, decodeContent(node));
607 node = nodeFactory.objectNode();
609 if (key.contains("@")) {
611 if (key.endsWith("@0") || jsonArray == null) {
612 jsonArray = new JSONArray();
614 } else if (!key.contains("@")) {
618 if (oldValue == null) {
619 oldValue = key.substring(0, key.indexOf('@'));
621 if (oldValue != prevKey) {
622 oldValue = key.substring(0, key.indexOf('@'));
624 if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
625 jsonArray.put(value);
627 jsonResult.put(oldValue, jsonArray);
628 jsonArray = new JSONArray();
630 oldValue = key.substring(0, key.indexOf('@'));
632 jsonResult.put(key, value);
636 if (node.size() > 0) {
637 if (nodeKey.contains("@")) {
638 if (jsonArray == null) {
639 jsonArray = new JSONArray();
641 if (arryKey == null) {
642 arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
644 jsonArray.put(decodeContent(node));
645 jsonResult.put(arryKey, jsonArray);
648 jsonResult.put(nodeKey, decodeContent(node));
651 if (isArray && jsonArray.length() > 0) {
652 jsonResult.put(oldValue, jsonArray);
657 @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"},
658 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
659 public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
661 ObjectMapper mapper = new ObjectMapper();
662 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
663 JsonNode root = mapper.readTree(request.getReader());
665 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
666 String servicename = value.split("-v")[0];
667 String version = null;
668 if (value.contains("-v")) {
669 version = value.split("-v")[1];
671 MicroServiceModels returnModel = getAttributeObject(servicename, version);
673 MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
674 JSONObject jsonHdDefaultObj = null;
675 if (returnHeaderDefauls != null) {
676 jsonHdDefaultObj = new JSONObject();
677 jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
678 jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
679 jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
680 jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
681 jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
683 String headDefautlsData = "";
684 if (jsonHdDefaultObj != null) {
685 headDefautlsData = jsonHdDefaultObj.toString();
687 headDefautlsData = "null";
690 // Get all keys with "MANY-true" defined in their value from subAttribute
691 Set<String> allkeys = null;
692 if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
693 JSONObject json = new JSONObject(returnModel.getSub_attributes());
695 allkeys = allManyTrueKeys;
696 allManyTrueKeys = new HashSet<>();
697 LOGGER.info("allkeys : " + allkeys);
700 // Get element order info
701 String dataOrderInfo = returnModel.getDataOrderInfo();
702 if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
703 dataOrderInfo = "\"" + dataOrderInfo + "\"";
705 LOGGER.info("dataOrderInfo : " + dataOrderInfo);
707 String allManyTrueKeys = "";
708 if (allkeys != null) {
709 allManyTrueKeys = allkeys.toString();
712 String jsonModel = createMicroSeriveJson(returnModel, allkeys);
714 JSONObject jsonObject = new JSONObject(jsonModel);
716 JSONObject finalJsonObject = null;
717 if (allkeys != null) {
718 Iterator<String> iter = allkeys.iterator();
719 while (iter.hasNext()) {
720 // Convert to array values for MANY-true keys
721 finalJsonObject = convertToArrayElement(jsonObject, iter.next());
725 if (finalJsonObject != null) {
726 LOGGER.info(finalJsonObject.toString());
727 jsonModel = finalJsonObject.toString();
730 // get all properties with "MANY-true" defined in Ref_attributes
731 Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
732 if (manyTrueProperties != null) {
733 JSONObject jsonObj = new JSONObject(jsonModel);
734 for (String s : manyTrueProperties) {
736 // convert to array element for MANY-true properties
737 finalJsonObject = convertToArrayElement(jsonObj, s.trim());
740 if (finalJsonObject != null) {
741 LOGGER.info(finalJsonObject.toString());
742 jsonModel = finalJsonObject.toString();
746 response.setCharacterEncoding("UTF-8");
747 response.setContentType("application / json");
748 request.setCharacterEncoding("UTF-8");
749 List<Object> list = new ArrayList<>();
750 PrintWriter out = response.getWriter();
751 String responseString = mapper.writeValueAsString(returnModel);
755 if ("".equals(allManyTrueKeys)) {
756 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
757 + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
759 j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
760 + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
764 out.write(list.toString());
768 @SuppressWarnings({"unchecked", "rawtypes"})
769 private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
770 Map<String, String> attributeMap = new HashMap<>();
771 Map<String, String> refAttributeMap = new HashMap<>();
772 String attribute = returnModel.getAttributes();
773 if (attribute != null) {
774 attribute = attribute.trim();
776 String refAttribute = returnModel.getRef_attributes();
777 if (refAttribute != null) {
778 refAttribute = refAttribute.trim();
780 String enumAttribute = returnModel.getEnumValues();
781 if (enumAttribute != null) {
782 enumAttribute = enumAttribute.trim();
784 if (!StringUtils.isEmpty(attribute)) {
785 attributeMap = convert(attribute, ",");
787 if (!StringUtils.isEmpty(refAttribute)) {
788 refAttributeMap = convert(refAttribute, ",");
791 Gson gson = new Gson();
793 String subAttributes = returnModel.getSub_attributes();
794 if (subAttributes != null) {
795 subAttributes = subAttributes.trim();
800 Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
802 JSONObject object = new JSONObject();
803 JSONArray array = new JSONArray();
805 for (Entry<String, String> keySet : attributeMap.entrySet()) {
806 array = new JSONArray();
807 String value = keySet.getValue();
808 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
810 object.put(keySet.getKey().trim(), array);
812 object.put(keySet.getKey().trim(), value.trim());
816 for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
817 array = new JSONArray();
818 String value = keySet.getValue().split(":")[0];
819 if (gsonObject.containsKey(value)) {
820 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
821 array.put(recursiveReference(value, gsonObject, enumAttribute));
822 object.put(keySet.getKey().trim(), array);
824 object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
827 if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
828 array.put(value.trim());
829 object.put(keySet.getKey().trim(), array);
831 object.put(keySet.getKey().trim(), value.trim());
836 return object.toString();
839 @SuppressWarnings("unchecked")
840 private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
841 JSONObject object = new JSONObject();
842 Map<String, String> map;
843 Object returnClass = subAttributeMap.get(name);
844 map = (Map<String, String>) returnClass;
847 for (Entry<String, String> m : map.entrySet()) {
848 String[] splitValue = m.getValue().split(":");
849 array = new JSONArray();
850 if (subAttributeMap.containsKey(splitValue[0])) {
851 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
852 array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
853 object.put(m.getKey().trim(), array);
855 object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
858 if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
859 array.put(splitValue[0].trim());
860 object.put(m.getKey().trim(), array);
862 object.put(m.getKey().trim(), splitValue[0].trim());
871 public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
872 return convertToArrayElement(json, new HashSet<>(), keyValue);
875 private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
876 for (String key : json.keySet()) {
877 Object obj = json.get(key);
878 if (key.equals(keyValue.trim())) {
879 if (!(obj instanceof JSONArray)) {
880 JSONArray newJsonArray = new JSONArray();
881 newJsonArray.put(obj);
882 json.put(key, newJsonArray);
884 LOGGER.info("key : " + key);
885 LOGGER.info("obj : " + obj);
886 LOGGER.info("json.get(key) : " + json.get(key));
887 LOGGER.info("keyValue : " + keyValue);
888 keys.addAll(json.keySet());
893 if (obj instanceof JSONObject)
894 convertToArrayElement(json.getJSONObject(key), keyValue);
900 // call this method to get all MANY-true properties
901 public static Set<String> getManyTrueProperties(String referAttributes) {
902 LOGGER.info("referAttributes : " + referAttributes);
903 Set<String> manyTrueProperties = new HashSet<>();
905 if (referAttributes != null) {
906 String[] referAarray = referAttributes.split(",");
907 String[] element = null;
908 for (int i = 0; i < referAarray.length; i++) {
909 element = referAarray[i].split("=");
910 if (element.length > 1 && element[1].contains("MANY-true")) {
911 manyTrueProperties.add(element[0]);
916 return manyTrueProperties;
919 // call this method to start the recursive
920 private Set<String> getAllKeys(JSONObject json) {
921 return getAllKeys(json, new HashSet<>());
924 private Set<String> getAllKeys(JSONArray arr) {
925 return getAllKeys(arr, new HashSet<>());
928 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
929 for (int i = 0; i < arr.length(); i++) {
930 Object obj = arr.get(i);
931 if (obj instanceof JSONObject)
932 keys.addAll(getAllKeys(arr.getJSONObject(i)));
933 if (obj instanceof JSONArray)
934 keys.addAll(getAllKeys(arr.getJSONArray(i)));
940 // this method returns a set of keys with "MANY-true" defined in their value.
941 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
942 for (String key : json.keySet()) {
943 Object obj = json.get(key);
944 if (obj instanceof String && ((String) obj).contains("MANY-true")) {
945 LOGGER.info("key : " + key);
946 LOGGER.info("obj : " + obj);
947 allManyTrueKeys.add(key);
949 if (obj instanceof JSONObject)
950 keys.addAll(getAllKeys(json.getJSONObject(key)));
951 if (obj instanceof JSONArray)
952 keys.addAll(getAllKeys(json.getJSONArray(key)));
959 @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"},
960 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
961 public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
963 ObjectMapper mapper = new ObjectMapper();
964 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
965 JsonNode root = mapper.readTree(request.getReader());
967 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
968 String servicename = value.split("-v")[0];
969 Set<String> returnList = getVersionList(servicename);
971 response.setCharacterEncoding("UTF-8");
972 response.setContentType("application / json");
973 request.setCharacterEncoding("UTF-8");
974 List<Object> list = new ArrayList<>();
975 PrintWriter out = response.getWriter();
976 String responseString = mapper.writeValueAsString(returnList);
977 JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
979 out.write(list.toString());
983 private Set<String> getVersionList(String name) {
984 MicroServiceModels workingModel;
985 Set<String> list = new HashSet<>();
986 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
987 for (int i = 0; i < microServiceModelsData.size(); i++) {
988 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
989 if (workingModel.getVersion() != null) {
990 list.add(workingModel.getVersion());
998 private MicroServiceModels getAttributeObject(String name, String version) {
999 MicroServiceModels workingModel = new MicroServiceModels();
1000 List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
1001 for (int i = 0; i < microServiceModelsData.size(); i++) {
1002 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
1003 if (version != null) {
1004 if (workingModel.getVersion() != null) {
1005 if (workingModel.getVersion().equals(version)) {
1006 return workingModel;
1009 return workingModel;
1012 return workingModel;
1016 return workingModel;
1019 private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
1020 return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
1024 @RequestMapping(value = {"/get_DCAEPriorityValues"},
1025 method = {org.springframework.web.bind.annotation.RequestMethod.GET},
1026 produces = MediaType.APPLICATION_JSON_VALUE)
1027 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
1029 Map<String, Object> model = new HashMap<>();
1030 ObjectMapper mapper = new ObjectMapper();
1031 List<String> priorityList = new ArrayList<>();
1033 for (int i = 1; i < priorityCount; i++) {
1034 priorityList.add(String.valueOf(i));
1036 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
1037 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
1038 JSONObject j = new JSONObject(msg);
1039 response.getWriter().write(j.toString());
1040 } catch (Exception e) {
1045 public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1046 if (policyAdapter.getPolicyData() instanceof PolicyType) {
1047 Object policyData = policyAdapter.getPolicyData();
1048 PolicyType policy = (PolicyType) policyData;
1049 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
1050 String policyNameValue =
1051 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
1052 policyAdapter.setPolicyName(policyNameValue);
1053 String description = "";
1055 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
1056 } catch (Exception e) {
1057 LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
1058 description = policy.getDescription();
1060 policyAdapter.setPolicyDescription(description);
1061 // Get the target data under policy.
1062 TargetType target = policy.getTarget();
1063 if (target != null) {
1064 // Under target we have AnyOFType
1065 List<AnyOfType> anyOfList = target.getAnyOf();
1066 if (anyOfList != null) {
1067 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
1068 while (iterAnyOf.hasNext()) {
1069 AnyOfType anyOf = iterAnyOf.next();
1070 // Under AnyOFType we have AllOFType
1071 List<AllOfType> allOfList = anyOf.getAllOf();
1072 if (allOfList != null) {
1073 Iterator<AllOfType> iterAllOf = allOfList.iterator();
1074 while (iterAllOf.hasNext()) {
1075 AllOfType allOf = iterAllOf.next();
1076 // Under AllOFType we have Match
1077 List<MatchType> matchList = allOf.getMatch();
1078 if (matchList != null) {
1079 Iterator<MatchType> iterMatch = matchList.iterator();
1080 while (matchList.size() > 1 && iterMatch.hasNext()) {
1081 MatchType match = iterMatch.next();
1083 // Under the match we have attribute value and
1084 // attributeDesignator. So,finally down to the actual attribute.
1086 AttributeValueType attributeValue = match.getAttributeValue();
1087 String value = (String) attributeValue.getContent().get(0);
1088 AttributeDesignatorType designator = match.getAttributeDesignator();
1089 String attributeId = designator.getAttributeId();
1090 // First match in the target is OnapName, so set that value.
1091 if ("ONAPName".equals(attributeId)) {
1092 policyAdapter.setOnapName(value);
1094 if ("ConfigName".equals(attributeId)) {
1095 policyAdapter.setConfigName(value);
1097 if ("uuid".equals(attributeId)) {
1098 policyAdapter.setUuid(value);
1100 if ("location".equals(attributeId)) {
1101 policyAdapter.setLocation(value);
1103 if ("RiskType".equals(attributeId)) {
1104 policyAdapter.setRiskType(value);
1106 if ("RiskLevel".equals(attributeId)) {
1107 policyAdapter.setRiskLevel(value);
1109 if ("guard".equals(attributeId)) {
1110 policyAdapter.setGuard(value);
1112 if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
1113 PolicyController controller = new PolicyController();
1114 String newDate = controller.convertDate(value);
1115 policyAdapter.setTtlDate(newDate);
1118 readFile(policyAdapter, entity);
1128 public static Map<String, String> convert(String str, String split) {
1129 Map<String, String> map = new HashMap<>();
1130 for (final String entry : str.split(split)) {
1131 String[] parts = entry.split("=");
1132 map.put(parts[0], parts[1]);
1138 @SuppressWarnings("unchecked")
1139 private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
1140 String policyScopeName = null;
1141 ObjectMapper mapper = new ObjectMapper();
1143 DCAEMicroServiceObject msBody =
1144 mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
1145 policyScopeName = getPolicyScope(msBody.getPolicyScope());
1146 policyAdapter.setPolicyScope(policyScopeName);
1148 policyAdapter.setPriority(msBody.getPriority());
1150 if (msBody.getVersion() != null) {
1151 policyAdapter.setServiceType(msBody.getService());
1152 policyAdapter.setVersion(msBody.getVersion());
1154 policyAdapter.setServiceType(msBody.getService());
1156 if (msBody.getContent() != null) {
1157 LinkedHashMap<String, Object> data = new LinkedHashMap<>();
1158 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
1159 readRecursivlyJSONContent(map, data);
1160 policyAdapter.setRuleData(data);
1163 } catch (Exception e) {
1169 @SuppressWarnings({"rawtypes", "unchecked"})
1170 public void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data) {
1171 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
1172 Object key = iterator.next();
1173 Object value = map.get(key);
1174 if (value instanceof LinkedHashMap<?, ?>) {
1175 LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
1176 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
1177 for (Entry<String, Object> entry : secondObjec.entrySet()) {
1178 data.put(key + "." + entry.getKey(), entry.getValue());
1180 } else if (value instanceof ArrayList) {
1181 ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
1182 for (int i = 0; i < jsonArrayVal.size(); i++) {
1183 Object arrayvalue = jsonArrayVal.get(i);
1184 if (arrayvalue instanceof LinkedHashMap<?, ?>) {
1185 LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
1186 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
1187 for (Entry<String, Object> entry : newData.entrySet()) {
1188 data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
1190 } else if (arrayvalue instanceof ArrayList) {
1191 ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
1192 for (int j = 0; j < jsonArrayVal1.size(); j++) {
1193 Object arrayvalue1 = jsonArrayVal1.get(i);
1194 data.put(key + "@" + j, arrayvalue1.toString());
1197 data.put(key + "@" + i, arrayvalue.toString());
1201 data.put(key.toString(), value.toString());
1206 public String getPolicyScope(String value) {
1207 List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
1208 if (groupList != null && !groupList.isEmpty()) {
1209 GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
1210 return pScope.getGroupName();
1215 // Convert the map values and set into JSON body
1216 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
1217 Map<String, String> attribute = new HashMap<>();
1221 for (Entry<String, String> entry : attributesMap.entrySet()) {
1222 key = entry.getKey();
1223 value = entry.getValue();
1224 attribute.put(key, value);
1226 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
1227 key = entryRef.getKey();
1228 value = entryRef.getValue();
1229 attribute.put(key, value);
1231 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
1232 key = entryList.getKey();
1233 value = entryList.getValue();
1234 attribute.put(key, value);
1236 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
1237 key = arrayList.getKey();
1239 for (Object textList : arrayList.getValue()) {
1241 temp = new StringBuilder();
1242 temp.append("[" + textList);
1244 temp.append("," + textList);
1247 attribute.put(key, temp + "]");
1253 @RequestMapping(value = {"/ms_dictionary/set_MSModelData"},
1254 method = {org.springframework.web.bind.annotation.RequestMethod.POST})
1255 public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
1256 throws IOException, FileUploadException {
1257 modelList = new ArrayList<>();
1258 dirDependencyList = new ArrayList<>();
1259 classMap = new LinkedHashMap<>();
1260 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
1261 boolean zip = false;
1262 boolean yml = false;
1263 String errorMsg = "";
1264 for (FileItem item : items) {
1265 if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
1266 this.newModel = new MicroServiceModels();
1268 File file = new File(item.getName());
1269 OutputStream outputStream = new FileOutputStream(file);
1270 IOUtils.copy(item.getInputStream(), outputStream);
1271 outputStream.close();
1272 this.newFile = file.toString();
1273 this.newModel.setModelName(this.newFile.split("-v")[0]);
1275 if (this.newFile.contains("-v")) {
1276 if (item.getName().endsWith(".zip")) {
1277 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
1279 } else if (item.getName().endsWith(".yml")) {
1280 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
1283 this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
1286 } catch (Exception e) {
1287 LOGGER.error("Upload error : ", e);
1288 errorMsg = "Upload error:" + e.getMessage();
1294 if (!errorMsg.isEmpty()) {
1296 PrintWriter out = response.getWriter();
1298 response.setCharacterEncoding("UTF-8");
1299 response.setContentType("application / json");
1300 request.setCharacterEncoding("UTF-8");
1302 JSONObject j = new JSONObject();
1303 j.put("errorMsg", errorMsg);
1304 out.write(j.toString());
1308 List<File> fileList = new ArrayList<>();
1309 MSModelUtils msMLUtils = new MSModelUtils();
1310 this.directory = "model";
1312 extractFolder(this.newFile);
1313 fileList = listModelFiles(this.directory);
1314 } else if (yml == true) {
1316 errorMsg = msMLUtils.parseTosca(this.newFile);
1317 if (errorMsg != null) {
1318 PrintWriter out = response.getWriter();
1319 response.setCharacterEncoding("UTF-8");
1320 response.setContentType("application / json");
1321 request.setCharacterEncoding("UTF-8");
1322 JSONObject j = new JSONObject();
1323 j.put("errorMsg", errorMsg);
1324 out.write(j.toString());
1329 File file = new File(this.newFile);
1332 String modelType = "";
1335 // Process Main Model file first
1336 classMap = new LinkedHashMap<>();
1337 for (File file : fileList) {
1338 if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
1339 retreiveDependency(file.toString(), true);
1343 modelList = createList();
1345 cleanUp(this.newFile);
1349 modelList.add(this.newModel.getModelName());
1350 String className = this.newModel.getModelName();
1351 MSAttributeObject msAttributes = new MSAttributeObject();
1352 msAttributes.setClassName(className);
1354 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
1355 returnAttributeList.put(className, msMLUtils.getAttributeString());
1356 msAttributes.setAttribute(returnAttributeList);
1358 msAttributes.setSubClass(msMLUtils.getRetmap());
1360 msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
1362 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
1364 returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
1365 msAttributes.setRefAttribute(returnReferenceList);
1367 if (msMLUtils.getListConstraints() != "") {
1368 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
1369 String[] listArray = msMLUtils.getListConstraints().split("#");
1370 for (String str : listArray) {
1371 String[] strArr = str.split("=");
1372 if (strArr.length > 1) {
1373 enumList.put(strArr[0], strArr[1]);
1376 msAttributes.setEnumType(enumList);
1379 classMap = new LinkedHashMap<>();
1380 classMap.put(className, msAttributes);
1384 PrintWriter out = response.getWriter();
1386 response.setCharacterEncoding("UTF-8");
1387 response.setContentType("application / json");
1388 request.setCharacterEncoding("UTF-8");
1390 ObjectMapper mapper = new ObjectMapper();
1391 JSONObject j = new JSONObject();
1392 j.put("classListDatas", modelList);
1393 j.put("modelDatas", mapper.writeValueAsString(classMap));
1394 j.put("modelType", modelType);
1395 j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
1397 out.write(j.toString());
1401 * Unzip file and store in the model directory for processing
1403 @SuppressWarnings("rawtypes")
1404 private void extractFolder(String zipFile) {
1406 File file = new File(zipFile);
1408 try (ZipFile zip = new ZipFile(file)) {
1409 String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1410 this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
1411 checkZipDirectory(this.directory);
1412 new File(newPath).mkdir();
1413 Enumeration zipFileEntries = zip.entries();
1415 // Process each entry
1416 while (zipFileEntries.hasMoreElements()) {
1417 // grab a zip file entry
1418 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
1419 String currentEntry = entry.getName();
1420 File destFile = new File("model" + File.separator + currentEntry);
1421 File destinationParent = destFile.getParentFile();
1423 destinationParent.mkdirs();
1425 if (!entry.isDirectory()) {
1426 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
1428 byte[] data = new byte[BUFFER];
1429 try (FileOutputStream fos = new FileOutputStream(destFile);
1430 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
1431 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
1432 dest.write(data, 0, currentByte);
1435 } catch (IOException e) {
1436 LOGGER.error("Failed to write zip contents to {}" + destFile + e);
1438 // PLD should I throw e?
1444 if (currentEntry.endsWith(".zip")) {
1445 extractFolder(destFile.getAbsolutePath());
1448 } catch (IOException e) {
1449 LOGGER.error("Failed to unzip model file " + zipFile, e);
1453 private void retreiveDependency(String workingFile, Boolean modelClass) {
1455 MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
1456 Map<String, MSAttributeObject> tempMap;
1458 tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
1460 classMap.putAll(tempMap);
1461 LOGGER.info(tempMap);
1467 private List<File> listModelFiles(String directoryName) {
1468 File fileDirectory = new File(directoryName);
1469 List<File> resultList = new ArrayList<>();
1470 File[] fList = fileDirectory.listFiles();
1471 for (File file : fList) {
1472 if (file.isFile()) {
1473 resultList.add(file);
1474 } else if (file.isDirectory()) {
1475 dirDependencyList.add(file.getName());
1476 resultList.addAll(listModelFiles(file.getAbsolutePath()));
1482 public void cleanUp(String path) {
1485 FileUtils.forceDelete(new File(path));
1486 } catch (IOException e) {
1487 LOGGER.error("Failed to delete folder " + path, e);
1492 public void checkZipDirectory(String zipDirectory) {
1493 Path path = Paths.get(zipDirectory);
1495 if (Files.exists(path)) {
1496 cleanUp(zipDirectory);
1500 private List<String> createList() {
1501 List<String> list = new ArrayList<>();
1502 for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
1503 if (cMap.getValue().isPolicyTempalate()) {
1504 list.add(cMap.getKey());
1509 if (list.isEmpty()) {
1510 if (classMap.containsKey(this.newModel.getModelName())) {
1511 list.add(this.newModel.getModelName());
1519 public Map<String, String> getAttributesListRefMap() {
1520 return attributesListRefMap;
1523 public Map<String, LinkedList<String>> getArrayTextList() {
1524 return arrayTextList;
1530 class DCAEMicroServiceObject {
1532 private String service;
1533 private String location;
1534 private String uuid;
1535 private String policyName;
1536 private String description;
1537 private String configName;
1538 private String templateVersion;
1539 private String version;
1540 private String priority;
1541 private String policyScope;
1542 private String riskType;
1543 private String riskLevel;
1544 private String guard = null;
1546 public String getGuard() {
1550 public void setGuard(String guard) {
1554 public String getRiskType() {
1558 public void setRiskType(String riskType) {
1559 this.riskType = riskType;
1562 public String getRiskLevel() {
1566 public void setRiskLevel(String riskLevel) {
1567 this.riskLevel = riskLevel;
1570 public String getPolicyScope() {
1574 public void setPolicyScope(String policyScope) {
1575 this.policyScope = policyScope;
1578 public String getPriority() {
1582 public void setPriority(String priority) {
1583 this.priority = priority;
1586 public String getVersion() {
1590 public void setVersion(String version) {
1591 this.version = version;
1594 private Object content;
1597 public String getPolicyName() {
1601 public void setPolicyName(String policyName) {
1602 this.policyName = policyName;
1605 public String getDescription() {
1609 public void setDescription(String description) {
1610 this.description = description;
1613 public String getConfigName() {
1617 public void setConfigName(String configName) {
1618 this.configName = configName;
1621 public Object getContent() {
1625 public void setContent(Object content) {
1626 this.content = content;
1629 public String getService() {
1633 public void setService(String service) {
1634 this.service = service;
1637 public String getLocation() {
1641 public void setLocation(String location) {
1642 this.location = location;
1645 public String getUuid() {
1649 public void setUuid(String uuid) {
1653 public String getTemplateVersion() {
1654 return templateVersion;
1657 public void setTemplateVersion(String templateVersion) {
1658 this.templateVersion = templateVersion;