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