From 1b9731632ba7cdc65780eba71aaebb5499faed51 Mon Sep 17 00:00:00 2001 From: "michele.artini" Date: Wed, 3 Feb 2021 16:42:36 +0100 Subject: [PATCH] Message Sender --- .../main/java/eu/dnetlib/message/Message.java | 13 ++++++- .../eu/dnetlib/message/MessageSender.java | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 dhp-common/src/main/java/eu/dnetlib/message/MessageSender.java diff --git a/dhp-common/src/main/java/eu/dnetlib/message/Message.java b/dhp-common/src/main/java/eu/dnetlib/message/Message.java index 8932e02f3..2de8ead42 100644 --- a/dhp-common/src/main/java/eu/dnetlib/message/Message.java +++ b/dhp-common/src/main/java/eu/dnetlib/message/Message.java @@ -1,9 +1,15 @@ package eu.dnetlib.message; +import java.io.Serializable; import java.util.Map; -public class Message { +public class Message implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 401753881204524893L; private String workflowId; @@ -55,4 +61,9 @@ public class Message { public void setBody(final Map body) { this.body = body; } + + @Override + public String toString() { + return String.format("Message [workflowId=%s, jobName=%s, type=%s, body=%s]", workflowId, jobName, type, body); + } } diff --git a/dhp-common/src/main/java/eu/dnetlib/message/MessageSender.java b/dhp-common/src/main/java/eu/dnetlib/message/MessageSender.java new file mode 100644 index 000000000..020d6087f --- /dev/null +++ b/dhp-common/src/main/java/eu/dnetlib/message/MessageSender.java @@ -0,0 +1,35 @@ + +package eu.dnetlib.message; + +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.SerializableEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MessageSender { + + private static final Logger log = LoggerFactory.getLogger(MessageSender.class); + + private final String dnetMessageEndpoint; + + public MessageSender(final String dnetMessageEndpoint) { + this.dnetMessageEndpoint = dnetMessageEndpoint; + } + + public void sendMessage(final Message message) { + final HttpPut req = new HttpPut(dnetMessageEndpoint); + req.setEntity(new SerializableEntity(message)); + + try (final CloseableHttpClient client = HttpClients.createDefault(); + final CloseableHttpResponse response = client.execute(req)) { + log.debug("Sent Message to " + dnetMessageEndpoint); + log.debug("MESSAGE:" + message); + } catch (final Throwable e) { + log.error("Error sending message to " + dnetMessageEndpoint + ", message content: " + message, e); + } + } + +}