47c33ca0b5a169931ed2eb02cc2abe285ce30f23
[appc.git] / appc-dg / appc-dg-shared / appc-dg-common / src / main / java / org / openecomp / appc / dg / common / impl / JsonDgUtilImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.dg.common.impl;
26
27 import java.io.File;
28 import java.text.SimpleDateFormat;
29 import java.util.Map;
30 import java.util.Set;
31
32 import org.apache.commons.lang3.ObjectUtils;
33 import org.apache.commons.lang3.StringUtils;
34 import org.openecomp.appc.dg.common.JsonDgUtil;
35 import org.openecomp.appc.exceptions.APPCException;
36 import org.openecomp.appc.i18n.Msg;
37 import org.openecomp.appc.util.JsonUtil;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
39
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import com.att.eelf.i18n.EELFResourceManager;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.fasterxml.jackson.databind.node.ArrayNode;
45 import com.fasterxml.jackson.databind.node.ObjectNode;
46
47
48 public class JsonDgUtilImpl implements JsonDgUtil {
49     private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class);
50
51     private static final ThreadLocal<SimpleDateFormat> DATE_TIME_PARSER_THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {
52         protected SimpleDateFormat initialValue() {
53             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
54         }
55     };
56
57     @Override
58     public void flatAndAddToContext(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
59
60         if (logger.isTraceEnabled()) {
61             logger.trace("Entering to flatAndAddToContext with params = "+ ObjectUtils.toString(params)+", SvcLogicContext = "+ObjectUtils.toString(ctx));
62         }
63         try {
64             String paramName = Constants.PAYLOAD;
65             String payload = params.get(paramName);
66             if (payload == "")
67                 payload = ctx.getAttribute("input.payload");
68             if (!StringUtils.isEmpty(payload)) {
69                 Map<String, String> flatMap = JsonUtil.convertJsonStringToFlatMap(payload);
70                 if (flatMap != null && flatMap.size() > 0) {
71                     for (Map.Entry<String, String> entry : flatMap.entrySet()) {
72                         ctx.setAttribute(entry.getKey(), entry.getValue());
73                     }
74                 }
75             } else {
76                 logger.warn("input payload param value is empty (\"\") or null");
77             }
78         } catch (Exception e) {
79             logger.error(e.toString());
80             String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED,params.get(Constants.PAYLOAD));
81             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
82             throw new APPCException(e);
83         }
84     }
85
86     @Override
87     public void generateOutputPayloadFromContext(Map<String, String> params, SvcLogicContext ctx) throws APPCException{
88         if (logger.isTraceEnabled()) {
89             logger.trace("Entering to generateOutputPayloadFromContext with SvcLogicContext = "+ObjectUtils.toString(ctx));
90         }
91
92         try {
93             Set<String> keys = ctx.getAttributeKeySet();
94             ObjectMapper objectMapper = new ObjectMapper();
95             ObjectNode JsonNode = objectMapper.createObjectNode();
96             for (String key : keys) {
97                 if(key.startsWith(Constants.OUTPUT_PAYLOAD+".")){
98                     String objkey=  key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", "");
99                     if(objkey.contains("[") && objkey.contains("]")){
100                         ArrayNode arrayNode;
101                         String arrayKey = objkey.substring(0,objkey.indexOf('['));
102                         int arrayIndex = Integer.parseInt(objkey.substring(objkey.indexOf('[')+1,objkey.indexOf(']')));
103                         if(JsonNode.has(arrayKey)){
104                             arrayNode = (ArrayNode)JsonNode.get(arrayKey);
105                             arrayNode.insert(arrayIndex,ctx.getAttribute(key));
106                         }else {
107                             arrayNode = objectMapper.createArrayNode();
108                             arrayNode.insert(arrayIndex,ctx.getAttribute(key));
109                             JsonNode.put(arrayKey,arrayNode);
110                         }
111                     }else {
112                         JsonNode.put(objkey, ctx.getAttribute(key));
113                     }
114                 }
115             }
116             if(JsonNode.size()>0) {
117                 ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(JsonNode));
118             }
119         } catch (Exception e) {
120             logger.error(e.toString());
121             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString());
122             throw new APPCException(e);
123         }
124
125     }
126
127     @Override
128     public void cvaasFileNameAndFileContentToContext(Map<String, String> params, SvcLogicContext ctx)
129             throws APPCException {
130
131         if (logger.isTraceEnabled()) {
132             logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = "
133                     + ObjectUtils.toString(ctx));
134         }
135
136         String vnfId = null;
137         try {
138             String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH);
139             String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID);
140
141                         /*
142                          * File name
143                          */
144             vnfId = params.get("vnf-id");
145             long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis();
146
147             ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_"
148                     + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json");
149
150                         /*
151                          * File content
152                          */
153
154             String uploadDate = ctx.getAttribute("running-config.upload-date");
155             long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime();
156
157             ObjectMapper objectMapper = new ObjectMapper();
158             ObjectNode jsonNode = objectMapper.createObjectNode();
159             jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id"));
160             jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id"));
161             jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id"));
162             jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description"));
163             jsonNode.put("ACTION", ctx.getAttribute("running-config.action"));
164             jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp);
165             jsonNode.put("UPLOAD_DATE", uploadDate);
166             jsonNode.put("VNF_ID", vnfId);
167             jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name"));
168             jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name"));
169             jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type"));
170             jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type"));
171             jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address"));
172             jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator"));
173             jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete"));
174             jsonNode.put("CONTENT", ctx.getAttribute("running-config.content"));
175
176             ctx.setAttribute(Constants.CVAAS_FILE_CONTENT,
177                     objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
178
179         } catch (Exception e) {
180             String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId;
181             logger.error(errorMessage, e);
182             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage);
183             throw new APPCException(e);
184         }
185     }
186
187     @Override
188     public void checkFileCreated(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
189         String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME);
190         File file = new File(filePath);
191
192         if (!file.exists()) {
193             String vnfId = params.get("vnf-id");
194             String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId;
195             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage);
196             throw new APPCException(errorMessage);
197         }
198     }
199 }