All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.elastic.sailor.impl.HttpReplyCallback Maven / Gradle / Ivy

There is a newer version: 4.0.3
Show newest version
package io.elastic.sailor.impl;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import io.elastic.api.EventEmitter;
import io.elastic.api.HttpReply;
import io.elastic.sailor.AmqpService;
import io.elastic.sailor.ExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class HttpReplyCallback implements EventEmitter.Callback {

    private static final Logger logger = LoggerFactory.getLogger(DataCallback.class);

    private AmqpService amqp;
    private CryptoServiceImpl cipher;
    private ExecutionContext executionContext;

    @Inject
    public HttpReplyCallback(
            final @Assisted ExecutionContext executionContext,
            final AmqpService amqp,
            final CryptoServiceImpl cipher) {
        this.executionContext = executionContext;
        this.amqp = amqp;
        this.cipher = cipher;
    }

    @Override
    public void receive(Object data) {
        final HttpReply reply = (HttpReply) data;

        final JsonObjectBuilder headers = Json.createObjectBuilder();
        reply.getHeaders().entrySet().stream().forEach(entry -> headers.add(entry.getKey(), entry.getValue()));

        final JsonObject payload = Json.createObjectBuilder()
                .add("statusCode", reply.getStatus())
                .add("body", getContentAsString(reply))
                .add("headers", headers.build())
                .build();
        // encrypt
        byte[] encryptedPayload = cipher.encryptJsonObject(payload).getBytes();

        amqp.sendHttpReply(encryptedPayload, executionContext.buildDefaultOptions());
    }

    private String getContentAsString(final HttpReply reply) {
        try {
            return inputStreamAsString(reply.getContent());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String inputStreamAsString(InputStream input) throws IOException {
        final StringWriter output = new StringWriter();
        final char[] buffer = new char[1024 * 4];
        final InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);

        int n = 0;
        while (-1 != (n = reader.read(buffer))) {
            output.write(buffer, 0, n);
        }

        return output.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy