<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.camel.component.slack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.component.slack.helper.SlackMessage;
import org.apache.camel.support.DefaultAsyncProducer;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.util.json.JsonObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.util.EntityUtils;

public class SlackProducer extends DefaultAsyncProducer {

    private final SlackEndpoint slackEndpoint;

    private CloseableHttpAsyncClient client;

    public SlackProducer(SlackEndpoint endpoint) {
        super(endpoint);
        this.slackEndpoint = endpoint;
    }

    @Override
    protected void doStart() throws Exception {
        this.client = HttpAsyncClientBuilder.create().useSystemProperties().build();
        super.doStart();
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();
        if (client != null) {
            client.close();
        }
    }

    @Override
    public boolean process(Exchange exchange, AsyncCallback callback) {

        // Create Post object
        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 = ExchangeHelper.getCharsetName(exchange, true);

        // Set the post body
        String json = asJson(slackMessage);
        StringEntity body = new StringEntity(json, charset);

        // Do the post
        httpPost.setEntity(body);

        client.execute(httpPost, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse response) {
                // 2xx is OK, anything else we regard as failure
                if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
                    exchange.setException(new CamelExchangeException("Error POSTing to Slack API: " + response.toString(), exchange));
                }
                EntityUtils.consumeQuietly(response.getEntity());
                callback.done(false);
            }
            @Override
            public void failed(Exception ex) {
                exchange.setException(ex);
                callback.done(false);
            }
            @Override
            public void cancelled() {
                callback.done(false);
            }
        });

        return false;
    }

    /**
     * Returns a JSON string to be posted to the Slack API
     *
     * @return JSON string
     */
    public String asJson(SlackMessage message) {
        Map<String, Object> jsonMap = new HashMap<>();

        // Put the values in a map
        jsonMap.put(SlackConstants.SLACK_TEXT_FIELD, message.getText());
        jsonMap.put(SlackConstants.SLACK_CHANNEL_FIELD, message.getChannel());
        jsonMap.put(SlackConstants.SLACK_USERNAME_FIELD, message.getUsername());
        jsonMap.put(SlackConstants.SLACK_ICON_URL_FIELD, message.getIconUrl());
        jsonMap.put(SlackConstants.SLACK_ICON_EMOJI_FIELD, message.getIconEmoji());

        List<SlackMessage.Attachment> attachments = message.getAttachments();
        if (attachments != null && !attachments.isEmpty()) {
            buildAttachmentJson(jsonMap, attachments);<commit_msg>Slack: Re-use http client and consume response (#4990)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.camel.component.slack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelExchangeException;
import org.apache.camel.Exchange;
import org.apache.camel.component.slack.helper.SlackMessage;
import org.apache.camel.support.DefaultAsyncProducer;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.util.json.JsonObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.util.EntityUtils;

public class SlackProducer extends DefaultAsyncProducer {

    private final SlackEndpoint slackEndpoint;
    private CloseableHttpAsyncClient client;

    public SlackProducer(SlackEndpoint endpoint) {
        super(endpoint);
        this.slackEndpoint = endpoint;
    }

    @Override
    protected void doStart() throws Exception {
        this.client = HttpAsyncClientBuilder.create().useSystemProperties().build();
        this.client.start();

        super.doStart();
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();

        if (client != null) {
            client.close();
            client = null;
        }
    }

    @Override
    public boolean process(Exchange exchange, AsyncCallback callback) {

        // Create Post object
        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 = ExchangeHelper.getCharsetName(exchange, true);

        // Set the post body
        String json = asJson(slackMessage);
        StringEntity body = new StringEntity(json, charset);

        // Do the post
        httpPost.setEntity(body);

        client.execute(httpPost, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse response) {
                // 2xx is OK, anything else we regard as failure
                if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
                    exchange.setException(
                            new CamelExchangeException("Error POSTing to Slack API: " + response.toString(), exchange));
                }
                EntityUtils.consumeQuietly(response.getEntity());
                callback.done(false);
            }

            @Override
            public void failed(Exception ex) {
                exchange.setException(ex);
                callback.done(false);
            }

            @Override
            public void cancelled() {
                callback.done(false);
            }
        });

        return false;
    }

    /**
     * Returns a JSON string to be posted to the Slack API
     *
     * @return JSON string
     */
    public String asJson(SlackMessage message) {
        Map<String, Object> jsonMap = new HashMap<>();

        // Put the values in a map
        jsonMap.put(SlackConstants.SLACK_TEXT_FIELD, message.getText());
        jsonMap.put(SlackConstants.SLACK_CHANNEL_FIELD, message.getChannel());
        jsonMap.put(SlackConstants.SLACK_USERNAME_FIELD, message.getUsername());
        jsonMap.put(SlackConstants.SLACK_ICON_URL_FIELD, message.getIconUrl());
        jsonMap.put(SlackConstants.SLACK_ICON_EMOJI_FIELD, message.getIconEmoji());

        List<SlackMessage.Attachment> attachments = message.getAttachments();
        if (attachments != null && !attachments.isEmpty()) {
            buildAttachmentJson(jsonMap, attachments);
{'fraction_non_alphanumeric': 0.0917851350062017, 'fraction_numerical': 0.0024806793244919376, 'mean_word_length': 2.860773480662983, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4559804', 'n_tokens_mistral': 2778, 'n_tokens_neox': 2688, 'n_words': 712}