Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
5.9 kB
1
Indexable
Never
package pl.inpost.parcellogisticstatusprovider.application.log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;

public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {

    private final byte[] cachedBody;

    public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        InputStream requestInputStream = request.getInputStream();
        this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
    }

    @Override
    public ServletInputStream getInputStream() {
        return new CachedBodyServletInputStream(this.cachedBody);
    }

    @Override
    public BufferedReader getReader() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
        return new BufferedReader(new InputStreamReader(byteArrayInputStream));
    }
}



package pl.inpost.parcellogisticstatusprovider.application.log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

public class CachedBodyServletInputStream extends ServletInputStream {

    private final InputStream cachedBodyInputStream;

    public CachedBodyServletInputStream(byte[] cachedBody) {
        this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
    }

    @Override
    public boolean isFinished() {
        try {
            return cachedBodyInputStream.available() == 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean isReady() {
        return true;
    }

    @Override
    public void setReadListener(ReadListener listener) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int read() throws IOException {
        return cachedBodyInputStream.read();
    }
}



package pl.inpost.parcellogisticstatusprovider.application.log;

import static feign.Util.decodeOrDefault;
import static feign.Util.toByteArray;
import static java.nio.charset.StandardCharsets.UTF_8;

import feign.Request;
import feign.Response;
import feign.Util;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class FeignLoggingInterceptor extends feign.Logger {

    private final Logger log;

    @Bean
    feign.Logger.Level feignLoggerLevel() {
        return Level.FULL;
    }

    @Override
    protected void log(String configKey, String format, Object... args) {
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        log.feignRequest(
            request.httpMethod().name(),
            request.url(),
            Util.decodeOrDefault(request.body(), UTF_8, null),
            request.requestTemplate().headers());
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        byte[] bodyBytes = toByteArray(response.body().asInputStream());
        String body = decodeOrDefault(bodyBytes, UTF_8, null);
        log.feignResponse(elapsedTime, body, response.status(), response.headers());

        return response.toBuilder().body(bodyBytes).build();
    }
}



package pl.inpost.parcellogisticstatusprovider.application.log;

import static java.util.Objects.isNull;
import static java.util.stream.Collectors.toMap;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import lombok.experimental.UtilityClass;
import org.springframework.web.util.ContentCachingResponseWrapper;

@UtilityClass
public class RequestLoggingHelper {

    public String getRequestBody(CachedBodyHttpServletRequest wrapper) throws IOException {
        return isNull(wrapper) ? null : getBody(wrapper.getInputStream().readAllBytes(), wrapper.getCharacterEncoding());
    }

    public String getResponseBody(ContentCachingResponseWrapper wrapper) throws UnsupportedEncodingException {
        return isNull(wrapper) ? null : getBody(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
    }

    private static String getBody(byte[] contentAsByteArray, String characterEncoding)
        throws UnsupportedEncodingException {
        if (contentAsByteArray.length > 0) {
            return new String(contentAsByteArray, 0, contentAsByteArray.length, characterEncoding)
                .replaceAll("\n", "")
                .replaceAll("\\s+", "");
        }
        return null;
    }

    public Map<String, String> getRequestHeaders(CachedBodyHttpServletRequest requestWrapper) {
        Map<String, String> result = new HashMap<>();
        Enumeration<String> headerNames = requestWrapper.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            result.put(name, requestWrapper.getHeader(name));
        }
        return result;
    }

    public Map<String, String> getResponseHeaders(ContentCachingResponseWrapper responseWrapper) {
        Collection<String> headerNames = responseWrapper.getHeaderNames();
        if (isNull(headerNames)) {
            return Collections.emptyMap();
        }
        return headerNames.stream()
            .distinct()
            .collect(toMap(r -> r, responseWrapper::getHeader));
    }
}