16488e2426b0164555db0eb763a5a5846bf9778b
[appc.git] / appc-dg / appc-dg-shared / appc-dg-common / src / main / java / org / onap / 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.onap.appc.dg.common.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.eelf.i18n.EELFResourceManager;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.node.ArrayNode;
32 import com.fasterxml.jackson.databind.node.ObjectNode;
33 import java.io.File;
34 import java.text.SimpleDateFormat;
35 import java.util.Map;
36 import java.util.Set;
37 import org.apache.commons.lang.ObjectUtils;
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.appc.dg.common.JsonDgUtil;
40 import org.onap.appc.exceptions.APPCException;
41 import org.onap.appc.i18n.Msg;
42 import org.onap.appc.util.JsonUtil;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44
45
46 public class JsonDgUtilImpl implements JsonDgUtil {
47
48     private static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonDgUtilImpl.class);
49
50     private static final ThreadLocal<SimpleDateFormat> DATE_TIME_PARSER_THREAD_LOCAL = ThreadLocal
51         .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
52
53     @Override
54     public void flatAndAddToContext(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
55
56         if (logger.isTraceEnabled()) {
57             logger.trace(
58                 "Entering to flatAndAddToContext with params = " + ObjectUtils.toString(params) + ", SvcLogicContext = "
59                     + ObjectUtils.toString(ctx));
60         }
61         try {
62             String paramName = Constants.PAYLOAD;
63             String payload = params.get(paramName);
64             if (payload == null || payload.isEmpty()) {
65                 payload = ctx.getAttribute("input.payload");
66             }
67             if (!StringUtils.isEmpty(payload)) {
68                 Map<String, String> flatMap = JsonUtil.convertJsonStringToFlatMap(payload);
69                 tryUpdateContext(ctx, flatMap);
70             } else {
71                 logger.warn("input payload param value is empty (\"\") or null");
72             }
73         } catch (Exception e) {
74             logger.error(e.toString());
75             String msg = EELFResourceManager.format(Msg.INPUT_PAYLOAD_PARSING_FAILED, params.get(Constants.PAYLOAD));
76             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
77             throw new APPCException(e);
78         }
79     }
80
81     private void tryUpdateContext(SvcLogicContext ctx, Map<String, String> flatMap) {
82         if (flatMap != null && flatMap.size() > 0) {
83             for (Map.Entry<String, String> entry : flatMap.entrySet()) {
84                 ctx.setAttribute(entry.getKey(), entry.getValue());
85             }
86         }
87     }
88
89     @Override
90     public void generateOutputPayloadFromContext(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
91         if (logger.isTraceEnabled()) {
92             logger.trace(
93                 "Entering to generateOutputPayloadFromContext with SvcLogicContext = " + ObjectUtils.toString(ctx));
94         }
95
96         try {
97             Set<String> keys = ctx.getAttributeKeySet();
98             ObjectMapper objectMapper = new ObjectMapper();
99             ObjectNode jsonNode = objectMapper.createObjectNode();
100             for (String key : keys) {
101                 updateJsonNode(ctx, objectMapper, jsonNode, key);
102             }
103             if (jsonNode.size() > 0) {
104                 ctx.setAttribute(Constants.OUTPUT_PAYLOAD, objectMapper.writeValueAsString(jsonNode));
105             }
106         } catch (Exception e) {
107             logger.error(e.toString());
108             ctx.setAttribute(Constants.DG_OUTPUT_STATUS_MESSAGE, e.toString());
109             throw new APPCException(e);
110         }
111
112     }
113
114     private void updateJsonNode(SvcLogicContext ctx, ObjectMapper objectMapper, ObjectNode jsonNode, String key) {
115         if (key.startsWith(Constants.OUTPUT_PAYLOAD + ".")) {
116             String objkey = key.replaceFirst(Constants.OUTPUT_PAYLOAD + ".", "");
117             if (objkey.contains("[") && objkey.contains("]")) {
118                 ArrayNode arrayNode;
119                 String arrayKey = objkey.substring(0, objkey.indexOf('['));
120                 int arrayIndex = Integer
121                     .parseInt(objkey.substring(objkey.indexOf('[') + 1, objkey.indexOf(']')));
122                 if (jsonNode.has(arrayKey)) {
123                     arrayNode = (ArrayNode) jsonNode.get(arrayKey);
124                     arrayNode.insert(arrayIndex, ctx.getAttribute(key));
125                 } else {
126                     arrayNode = objectMapper.createArrayNode();
127                     arrayNode.insert(arrayIndex, ctx.getAttribute(key));
128                     jsonNode.put(arrayKey, arrayNode);
129                 }
130             } else {
131                 jsonNode.put(objkey, ctx.getAttribute(key));
132             }
133         }
134     }
135
136     @Override
137     public void cvaasFileNameAndFileContentToContext(Map<String, String> params, SvcLogicContext ctx)
138         throws APPCException {
139
140         if (logger.isTraceEnabled()) {
141             logger.trace("Entering to caasFileNameAndFileContentToContext with SvcLogicContext = "
142                 + ObjectUtils.toString(ctx));
143         }
144
145         String vnfId = null;
146         try {
147             String cvassDirectoryPath = params.get(Constants.CVAAS_DIRECTORY_PATH);
148             String appcInstanceId = params.get(Constants.APPC_INSTANCE_ID);
149
150                         /*
151              * File name
152                          */
153             vnfId = params.get("vnf-id");
154             long timestampAsLongRepresentingFileCreationTime = System.currentTimeMillis();
155
156             ctx.setAttribute(Constants.CVAAS_FILE_NAME, cvassDirectoryPath + File.separator + vnfId + "_"
157                 + timestampAsLongRepresentingFileCreationTime + "_" + appcInstanceId + ".json");
158
159                         /*
160                          * File content
161                          */
162
163             String uploadDate = ctx.getAttribute("running-config.upload-date");
164             long epochUploadTimestamp = DATE_TIME_PARSER_THREAD_LOCAL.get().parse(uploadDate).getTime();
165
166             ObjectMapper objectMapper = new ObjectMapper();
167             ObjectNode jsonNode = objectMapper.createObjectNode();
168             jsonNode.put("UPLOAD_CONFIG_ID", ctx.getAttribute("running-config.upload-config-id"));
169             jsonNode.put("REQUEST_ID", ctx.getAttribute("running-config.request-id"));
170             jsonNode.put("ORIGINATOR_ID", ctx.getAttribute("running-config.originator-id"));
171             jsonNode.put("SERVICE_DESCRIPTION", ctx.getAttribute("running-config.service-description"));
172             jsonNode.put("ACTION", ctx.getAttribute("running-config.action"));
173             jsonNode.put("UPLOAD_TIMESTAMP", epochUploadTimestamp);
174             jsonNode.put("UPLOAD_DATE", uploadDate);
175             jsonNode.put("VNF_ID", vnfId);
176             jsonNode.put("VNF_NAME", ctx.getAttribute("running-config.vnf-name"));
177             jsonNode.put("VM_NAME", ctx.getAttribute("running-config.vm-name"));
178             jsonNode.put("VNF_TYPE", ctx.getAttribute("running-config.vnf-type"));
179             jsonNode.put("VNFC_TYPE", ctx.getAttribute("running-config.vnfc-type"));
180             jsonNode.put("HOST_IP_ADDRESS", ctx.getAttribute("running-config.host-ip-address"));
181             jsonNode.put("CONFIG_INDICATOR", ctx.getAttribute("running-config.config-indicator"));
182             jsonNode.put("PENDING_DELETE", ctx.getAttribute("running-config.pending-delete"));
183             jsonNode.put("CONTENT", ctx.getAttribute("running-config.content"));
184
185             ctx.setAttribute(Constants.CVAAS_FILE_CONTENT,
186                 objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
187
188         } catch (Exception e) {
189             String errorMessage = "Failed to parse create cvass file for vnf with id : " + vnfId;
190             logger.error(errorMessage, e);
191             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage);
192             throw new APPCException(e);
193         }
194     }
195
196     @Override
197     public void checkFileCreated(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
198         String filePath = ctx.getAttribute(Constants.CVAAS_FILE_NAME);
199         File file = new File(filePath);
200
201         if (!file.exists()) {
202             String vnfId = params.get("vnf-id");
203             String errorMessage = "Cvass file could not be created for vnf with id : " + vnfId;
204             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, errorMessage);
205             throw new APPCException(errorMessage);
206         }
207     }
208 }