Merge of new rebased code
[appc.git] / appc-dispatcher / appc-request-handler / appc-request-handler-core / src / main / java / org / openecomp / appc / messageadapter / impl / MessageAdapterImpl.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.messageadapter.impl;
23
24
25 import org.openecomp.appc.adapter.factory.DmaapMessageAdapterFactoryImpl;
26 import org.openecomp.appc.adapter.factory.MessageService;
27 import org.openecomp.appc.adapter.message.MessageAdapterFactory;
28 import org.openecomp.appc.adapter.message.Producer;
29 import org.openecomp.appc.configuration.Configuration;
30 import org.openecomp.appc.configuration.ConfigurationFactory;
31 import com.att.eelf.configuration.EELFLogger;
32 import com.att.eelf.configuration.EELFManager;
33
34 import com.fasterxml.jackson.core.JsonProcessingException;
35 import org.apache.commons.lang.ObjectUtils;
36 import org.openecomp.appc.domainmodel.lcm.ResponseContext;
37 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
38 import org.openecomp.appc.messageadapter.MessageAdapter;
39 import org.openecomp.appc.requesthandler.conv.Converter;
40 import org.osgi.framework.BundleContext;
41 import org.osgi.framework.FrameworkUtil;
42 import org.osgi.framework.ServiceReference;
43
44 import java.util.HashSet;
45 import java.util.Properties;
46
47 public class MessageAdapterImpl implements MessageAdapter{
48
49     private MessageService messageService;
50     private Producer producer;
51     private String partition ;
52     private Configuration configuration;
53     private HashSet<String> pool;
54     private String writeTopic;
55     private String apiKey;
56     private String apiSecret;
57
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class);
59
60     /**
61      * Initialize producer client to post messages using configuration properties
62      */
63     @Override
64     public void init(){
65         this.producer = getProducer();
66     }
67
68     private Producer getProducer() {
69         configuration = ConfigurationFactory.getConfiguration();
70         Properties properties=configuration.getProperties();
71         updateProperties(properties);
72         
73         BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext();
74         if (ctx != null) {
75                 ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
76                 if (svcRef != null) {
77                         producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret);
78                 }
79         }
80         return producer;
81     }
82
83
84     private void updateProperties(Properties props) {
85         if (logger.isTraceEnabled()) {
86             logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props));
87         }
88         pool = new HashSet<>();
89         if (props != null) {
90             // readTopic = props.getProperty("dmaap.topic.read");
91             writeTopic = props.getProperty("appc.LCM.topic.write");
92             apiKey = props.getProperty("appc.LCM.client.key");
93             apiSecret = props.getProperty("appc.LCM.client.secret");
94             messageService = MessageService.parse(props.getProperty("message.service.type"));
95             //  READ_TIMEOUT = Integer.valueOf(props.getProperty("dmaap.topic.read.timeout", String.valueOf(READ_TIMEOUT)));
96             String hostnames = props.getProperty("appc.LCM.poolMembers");
97             if (hostnames != null && !hostnames.isEmpty()) {
98                 for (String name : hostnames.split(",")) {
99                     pool.add(name);
100                 }
101             }
102         }
103     }
104
105     /**
106      * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP.
107      * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel).
108      * @return True if message is postes successfully else False
109      */
110     @Override
111     public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){
112         boolean success;
113         if (logger.isTraceEnabled()) {
114             logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse));
115         }
116
117         String jsonMessage;
118         try {
119             jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse);
120             if (logger.isDebugEnabled()) {
121                 logger.debug("DMaaP Response = " + jsonMessage);
122             }
123             success  = producer.post(this.partition, jsonMessage);
124         } catch (JsonProcessingException e1) {
125             logger.error("Error generating Json from DMaaP message "+ e1.getMessage());
126             success= false;
127         }catch (Exception e){
128             logger.error("Error sending message to DMaaP "+e.getMessage());
129             success= false;
130         }
131         if (logger.isTraceEnabled()) {
132             logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")");
133         }
134         return success;
135     }
136 }