Merge of new rebased code
[appc.git] / appc-dg / appc-dg-shared / appc-dg-common / src / main / java / org / openecomp / appc / dg / common / impl / IntermediateMessageSenderImpl.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
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import com.fasterxml.jackson.databind.node.ObjectNode;
29 import org.apache.commons.lang.StringUtils;
30 import org.openecomp.appc.adapter.message.MessageAdapterFactory;
31 import org.openecomp.appc.adapter.message.Producer;
32 import org.openecomp.appc.configuration.Configuration;
33 import org.openecomp.appc.configuration.ConfigurationFactory;
34 import org.openecomp.appc.dg.common.IntermediateMessageSender;
35 import org.openecomp.appc.exceptions.APPCException;
36 import org.openecomp.sdnc.sli.SvcLogicContext;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.FrameworkUtil;
39 import org.osgi.framework.ServiceReference;
40
41 import java.util.HashSet;
42 import java.util.Map;
43 import java.util.Properties;
44 import java.util.Set;
45
46 public class IntermediateMessageSenderImpl implements IntermediateMessageSender {
47
48
49     private Producer producer;
50
51     private Configuration configuration;
52
53     private final EELFLogger logger = EELFManager.getInstance().getLogger(IntermediateMessageSenderImpl.class);
54
55     private static final String STATUS = "STATUS";
56     private static final String FAILURE = "FAILURE";
57     private static final String SUCCESS = "SUCCESS";
58     private static final String ERROR_MESSAGE = "ERROR_MESSAGE";
59
60     private static final String RESPONSE = "response";
61     private static final String MSO = "MSO";
62
63     public void init(){
64         configuration = ConfigurationFactory.getConfiguration();
65         Properties properties=configuration.getProperties();
66
67         String writeTopic = properties.getProperty("appc.LCM.topic.write");
68         String apiKey = properties.getProperty("appc.LCM.client.key");
69         String apiSecret = properties.getProperty("appc.LCM.client.secret");
70         String hostNames = properties.getProperty("appc.LCM.poolMembers");
71
72         logger.debug("Configuration Read : writeTopic = " + writeTopic +", " +
73                                             "hostNames = " + hostNames);
74
75         Set<String> pool = new HashSet<>();
76         if (!StringUtils.isEmpty(hostNames)) {
77             for (String name : hostNames.split(",")) {
78                 pool.add(name);
79             }
80         }
81
82         BundleContext ctx = FrameworkUtil.getBundle(IntermediateMessageSenderImpl.class).getBundleContext();
83         if (ctx != null) {
84             ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
85             if (svcRef != null) {
86                 producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret);
87             }
88         }
89     }
90
91     @Override
92     public void sendMessage(Map<String, String> params, SvcLogicContext context) {
93         String prefix = params.get("prefix");
94         prefix = StringUtils.isEmpty(prefix)? "":prefix+".";
95         try{
96             validateInputs(params,context);
97             String jsonMessage = getJsonMessage(params, context);
98             logger.debug("Constructed JSON Message : " + jsonMessage);
99             producer.post("",jsonMessage);
100             context.setAttribute(prefix + STATUS, SUCCESS);
101         }
102         catch(Exception e){
103             String errorMessage = "Error sending intermediate message to initiator " + e.getMessage();
104             context.setAttribute(prefix + STATUS, FAILURE);
105             context.setAttribute(prefix + ERROR_MESSAGE, errorMessage);
106             logger.error(errorMessage,e);
107         }
108     }
109
110     private void validateInputs(Map<String, String> params, SvcLogicContext context) throws APPCException {
111         String code = params.get("code");
112         String message = params.get("message");
113         if(StringUtils.isEmpty(code) || StringUtils.isEmpty(message)){
114             throw new APPCException("code or message is empty");
115         }
116         String requestId = context.getAttribute("input.common-header.request-id");
117         if(StringUtils.isEmpty(requestId)){
118             throw new APPCException("requestId is empty");
119         }
120     }
121
122     private String getJsonMessage(Map<String, String> params, SvcLogicContext context) {
123         ObjectMapper objectMapper = new ObjectMapper();
124
125         ObjectNode commonHeader = getCommonHeader(context);
126         ObjectNode status = getStatus(params);
127
128         ObjectNode output = objectMapper.createObjectNode();
129         output.put("common-header",commonHeader);
130         output.put("status",status);
131
132         ObjectNode body =  objectMapper.createObjectNode();
133         body.put("output",output);
134
135         ObjectNode root = objectMapper.createObjectNode();
136         root.put("type", RESPONSE);
137         root.put("rpc-name",context.getAttribute("input.action"));
138         root.put("cambria.partition", MSO);
139         root.put("correlation-id",getCorrelationId(context));
140         root.put("body",body);
141
142         return root.toString();
143     }
144
145     private String getCorrelationId(SvcLogicContext context) {
146         String requestId = context.getAttribute("input.common-header.request-id");
147         String subRequestId = context.getAttribute("input.common-header.sub-request-id");
148         return requestId + (StringUtils.isEmpty(subRequestId)?"":("-"+subRequestId));
149     }
150
151     private ObjectNode getStatus(Map<String,String> params) {
152         ObjectMapper objectMapper = new ObjectMapper();
153         ObjectNode status =  objectMapper.createObjectNode();
154         status.put("code",params.get("code"));
155         status.put("message",params.get("message"));
156         return status;
157     }
158
159     private ObjectNode getCommonHeader(SvcLogicContext context) {
160         ObjectMapper objectMapper = new ObjectMapper();
161         ObjectNode commonHeader =  objectMapper.createObjectNode();
162         commonHeader.put("api-ver",context.getAttribute("input.common-header.api-ver"));
163         commonHeader.put("timestamp",context.getAttribute("input.common-header.timestamp"));
164         commonHeader.put("originator-id",context.getAttribute("input.common-header.originator-id"));
165         commonHeader.put("request-id",context.getAttribute("input.common-header.request-id"));
166         commonHeader.put("sub-request-id",context.getAttribute("input.common-header.sub-request-id"));
167         return commonHeader;
168     }
169 }