Search in sources :

Example 1 with SlackMessage

use of org.apache.camel.component.slack.helper.SlackMessage in project camel by apache.

the class SlackProducer method process.

@Override
public void process(Exchange exchange) throws Exception {
    // Create an HttpClient and Post object
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(slackEndpoint.getWebhookUrl());
    // Build Helper object
    SlackMessage slackMessage;
    Object payload = exchange.getIn().getBody();
    if (payload instanceof SlackMessage) {
        slackMessage = (SlackMessage) payload;
    } else {
        slackMessage = new SlackMessage();
        slackMessage.setText(exchange.getIn().getBody(String.class));
    }
    slackMessage.setChannel(slackEndpoint.getChannel());
    slackMessage.setUsername(slackEndpoint.getUsername());
    slackMessage.setIconUrl(slackEndpoint.getIconUrl());
    slackMessage.setIconEmoji(slackEndpoint.getIconEmoji());
    // use charset from exchange or fallback to the default charset
    String charset = IOHelper.getCharsetName(exchange, true);
    // Set the post body
    String json = asJson(slackMessage);
    StringEntity body = new StringEntity(json, charset);
    // Do the post
    httpPost.setEntity(body);
    HttpResponse response = client.execute(httpPost);
    // 2xx is OK, anything else we regard as failure
    if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
        throw new CamelExchangeException("Error POSTing to Slack API: " + response.toString(), exchange);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) CamelExchangeException(org.apache.camel.CamelExchangeException) HttpClient(org.apache.http.client.HttpClient) SlackMessage(org.apache.camel.component.slack.helper.SlackMessage) HttpResponse(org.apache.http.HttpResponse) JSONObject(org.json.simple.JSONObject)

Aggregations

CamelExchangeException (org.apache.camel.CamelExchangeException)1 SlackMessage (org.apache.camel.component.slack.helper.SlackMessage)1 HttpResponse (org.apache.http.HttpResponse)1 HttpClient (org.apache.http.client.HttpClient)1 HttpPost (org.apache.http.client.methods.HttpPost)1 StringEntity (org.apache.http.entity.StringEntity)1 JSONObject (org.json.simple.JSONObject)1