2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pap.main.comm;
23 import java.util.List;
25 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
26 import org.onap.policy.common.endpoints.event.comm.TopicSink;
27 import org.onap.policy.common.utils.coder.Coder;
28 import org.onap.policy.common.utils.coder.CoderException;
29 import org.onap.policy.common.utils.coder.StandardCoder;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Client for communication with PDPs.
36 public class PdpClient {
37 private static final Logger logger = LoggerFactory.getLogger(PdpClient.class);
40 * Coder used to encode messages being sent to PDPs.
42 private static final Coder CODER = new StandardCoder();
45 * Topic to which messages are published.
48 private final String topic;
51 * Where messages are published.
53 private final TopicSink sink;
56 * Constructs the object.
58 * @param topic topic to which messages should be published
59 * @throws PdpClientException if the topic does not exist
61 public PdpClient(String topic) throws PdpClientException {
64 List<TopicSink> lst = getTopicSinks(topic);
66 throw new PdpClientException("no sinks for topic: " + topic);
69 this.sink = lst.get(0);
73 * Sends a message to the PDPs via the topic, after encoding the message as json.
75 * @param message message to be encoded and sent
76 * @return {@code true} if the message was successfully sent/enqueued, {@code false}
79 public boolean send(Object message) {
81 String json = CODER.encode(message);
82 return sink.send(json);
84 } catch (RuntimeException | CoderException e) {
85 logger.warn("send to {} failed because of {}", topic, e.getMessage(), e);
90 // the remaining methods are wrappers that can be overridden by junit tests
93 * Gets the sinks for a given topic.
95 * @param topic the topic of interest
96 * @return the sinks for the topic
98 protected List<TopicSink> getTopicSinks(String topic) {
99 return TopicEndpoint.manager.getTopicSinks(topic);