1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
|
/*-
* ========================LICENSE_START=================================
* ONAP : ccsdk oran
* ======================================================================
* Copyright (C) 2020 Nordix Foundation. All rights reserved.
* ======================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================LICENSE_END===================================
*/
package org.onap.ccsdk.oran.a1policymanagementservice.dmaap;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapterFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
/**
* The class fetches incoming requests from DMAAP. It uses the timeout parameter
* that lets the MessageRouter keep the connection with the Kafka open until
* requests are sent in.
*
* <p>
* this service will regularly check the configuration and start polling DMaaP
* if the configuration is added. If the DMaaP configuration is removed, then
* the service will stop polling and resume checking for configuration.
*
* <p>
* Each received request is processed by {@link DmaapMessageHandler}.
*/
@Component
public class DmaapMessageConsumer {
protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
private final ApplicationConfig applicationConfig;
private DmaapMessageHandler dmaapMessageHandler = null;
private final Gson gson;
@Value("${server.http-port}")
private int localServerHttpPort;
@Autowired
public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
GsonBuilder gsonBuilder = new GsonBuilder();
ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
gson = gsonBuilder.create();
}
/**
* Starts the consumer. If there is a DMaaP configuration, it will start polling
* for messages. Otherwise it will check regularly for the configuration.
*
* @return the running thread, for test purposes.
*/
public Thread start() {
Thread thread = new Thread(this::messageHandlingLoop);
thread.start();
return thread;
}
private void messageHandlingLoop() {
while (!isStopped()) {
try {
if (isDmaapConfigured()) {
Iterable<DmaapRequestMessage> dmaapMsgs = fetchAllMessages();
if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
for (DmaapRequestMessage msg : dmaapMsgs) {
processMsg(msg);
}
}
} else {
sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
}
} catch (Exception e) {
logger.warn("{}", e.getMessage());
sleep(TIME_BETWEEN_DMAAP_RETRIES);
}
}
}
protected boolean isStopped() {
return false;
}
protected boolean isDmaapConfigured() {
String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
&& !consumerTopicUrl.isEmpty());
}
private <T> List<T> parseList(String jsonString, Class<T> clazz) {
List<T> result = new ArrayList<>();
JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
for (JsonElement jsonElement : jsonArr) {
// The element can either be a JsonObject or a JsonString
if (jsonElement.isJsonPrimitive()) {
T json = gson.fromJson(jsonElement.getAsString(), clazz);
result.add(json);
} else {
T json = gson.fromJson(jsonElement.toString(), clazz);
result.add(json);
}
}
return result;
}
private void sendErrorResponse(String response) {
DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
.apiVersion("") //
.correlationId("") //
.operation(DmaapRequestMessage.Operation.PUT) //
.originatorId("") //
.payload(Optional.empty()) //
.requestId("") //
.target("") //
.timestamp("") //
.url("URL") //
.build();
getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST).block();
}
List<DmaapRequestMessage> parseMessages(String jsonString) throws ServiceException {
try {
return parseList(jsonString, DmaapRequestMessage.class);
} catch (Exception e) {
sendErrorResponse("Not parsable request received, reason:" + e.toString() + ", input :" + jsonString);
throw new ServiceException("Could not parse incomming request. Reason :" + e.getMessage());
}
}
protected Iterable<DmaapRequestMessage> fetchAllMessages() throws ServiceException {
String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
AsyncRestClient consumer = getMessageRouterConsumer();
ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
if (response.getStatusCode().is2xxSuccessful()) {
return parseMessages(response.getBody());
} else {
throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
+ " " + response.getBody());
}
}
private void processMsg(DmaapRequestMessage msg) {
logger.debug("Message Reveived from DMAAP : {}", msg);
getDmaapMessageHandler().handleDmaapMsg(msg);
}
protected DmaapMessageHandler getDmaapMessageHandler() {
if (this.dmaapMessageHandler == null) {
String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
AsyncRestClient pmsClient = new AsyncRestClient(pmsBaseUrl, this.applicationConfig.getWebClientConfig());
AsyncRestClient producer = new AsyncRestClient(this.applicationConfig.getDmaapProducerTopicUrl(),
this.applicationConfig.getWebClientConfig());
this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
}
return this.dmaapMessageHandler;
}
protected void sleep(Duration duration) {
try {
Thread.sleep(duration.toMillis());
} catch (Exception e) {
logger.error("Failed to put the thread to sleep", e);
}
}
protected AsyncRestClient getMessageRouterConsumer() {
return new AsyncRestClient("", this.applicationConfig.getWebClientConfig());
}
}
|