Java源码示例:org.zalando.logbook.HttpRequest

示例1
private String responseMessage(final HttpRequest request, final HttpResponse response) {
    final String requestUri = request.getRequestUri();
    final StringBuilder messageBuilder = new StringBuilder(64 + requestUri.length());
    messageBuilder.append(response.getStatus());
    final String reasonPhrase = response.getReasonPhrase();
    if (reasonPhrase != null) {
        messageBuilder.append(' ');
        messageBuilder.append(reasonPhrase);
    }
    messageBuilder.append(' ');
    messageBuilder.append(request.getMethod());
    messageBuilder.append(' ');
    messageBuilder.append(requestUri);

    return messageBuilder.toString();
}
 
示例2
@API(status = EXPERIMENTAL)
public void prepare(
        final Precorrelation precorrelation,
        final HttpRequest request,
        final JsonGenerator generator) throws IOException {

    generator.writeStringField("origin",
            request.getOrigin() == LOCAL ? "local" : "remote");
    generator.writeStringField("type", "request");
    generator.writeStringField("correlation", precorrelation.getId());
    generator.writeStringField("protocol", request.getProtocolVersion());
    generator.writeStringField("remote", request.getRemote());
    generator.writeStringField("method", request.getMethod());
    generator.writeStringField("uri", reconstructUri(request));

    writeHeaders(request, generator);
    writeBody(request, generator);
}
 
示例3
@ParameterizedTest
@MethodSource("units")
void shouldLogRequestWithoutContentType(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTP/1.0")
            .withOrigin(REMOTE)
            .withPath("/test")
            .withBodyAsString("Hello");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.origin", is("remote"))
            .assertThat("$.type", is("request"))
            .assertThat("$.correlation", is("3ce91230-677b-11e5-87b7-10ddb1ee7671"))
            .assertThat("$.protocol", is("HTTP/1.0"))
            .assertThat("$.remote", is("127.0.0.1"))
            .assertThat("$.method", is("GET"))
            .assertThat("$.uri", is("http://localhost/test"))
            .assertThat("$.body", is("Hello"));
}
 
示例4
@ParameterizedTest
@MethodSource("units")
void shouldLogCorrectRequestOrigin(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "53de2640-677d-11e5-bc84-10ddb1ee7671";
    final HttpRequest local = MockHttpRequest.create().withOrigin(LOCAL);
    final String localJson = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), local);

    with(localJson)
            .assertThat("$.origin", is("local"));

    final HttpRequest remote = MockHttpRequest.create().withOrigin(REMOTE);
    final String remoteJson = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), remote);

    with(remoteJson)
            .assertThat("$.origin", is("remote"));

}
 
示例5
@ParameterizedTest
@MethodSource("units")
void shouldLogNonstandardHttpsPort(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTPS/1.0")
            .withScheme("https")
            .withOrigin(REMOTE)
            .withPort(Optional.of(123))
            .withPath("/test");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.uri", is("https://localhost:123/test"));
}
 
示例6
@ParameterizedTest
@MethodSource("units")
void shouldNotLogStandardHttpsPort(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTPS/1.0")
            .withScheme("https")
            .withOrigin(REMOTE)
            .withPort(Optional.of(443))
            .withPath("/test");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.uri", is("https://localhost/test"));
}
 
示例7
@ParameterizedTest
@MethodSource("units")
void shouldNotLogStandardHttpPort(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTP/1.0")
            .withScheme("http")
            .withOrigin(REMOTE)
            .withPort(Optional.of(80))
            .withPath("/test");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.uri", is("http://localhost/test"));
}
 
示例8
@ParameterizedTest
@MethodSource("units")
void shouldNotLogMissingPort(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTP/1.0")
            .withScheme("http")
            .withOrigin(REMOTE)
            .withPort(Optional.empty())
            .withPath("/test");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.uri", is("http://localhost/test"));
}
 
示例9
@Test
void shouldFormatRequest() throws Exception {
    mvc.perform(get("/api/sync?limit=1")
            .accept(MediaType.TEXT_PLAIN));

    final HttpRequest request = interceptRequest();

    assertThat(request, hasFeature("remote address", HttpRequest::getRemote, is("127.0.0.1")));
    assertThat(request, hasFeature("method", HttpRequest::getMethod, is("GET")));
    assertThat(request, hasFeature("url", HttpRequest::getRequestUri,
            hasToString("http://localhost/api/sync?limit=1")));
    assertThat(request, hasFeature("query", HttpRequest::getQuery, is("limit=1")));
    assertThat(request, hasFeature("headers", HttpRequest::getHeaders,
            is(singletonMap("Accept", singletonList("text/plain")))));
    assertThat(request, hasFeature("body", this::getBody, is(notNullValue())));
    assertThat(request, hasFeature("body", this::getBodyAsString, is(emptyString())));
}
 
示例10
@Test
void shouldFilterAuthorizationByDefault() throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withHeaders(HttpHeaders.empty()
                    .update("Authorization", "123")
                    .update("X-Secret", "123"));

    logbook.process(request).write();

    final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(writer).write(any(Precorrelation.class), captor.capture());
    final String message = captor.getValue();

    assertThat(message, containsString("Authorization: XXX"));
    assertThat(message, containsString("X-Secret: 123"));
}
 
示例11
@Test
void shouldFilterHeaders() throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withHeaders(HttpHeaders.empty()
                    .update("Authorization", "123")
                    .update("X-Access-Token", "123")
                    .update("X-Trace-ID", "ABC"));

    logbook.process(request).write();

    final ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(writer).write(any(Precorrelation.class), captor.capture());
    final String message = captor.getValue();

    assertThat(message, containsString("Authorization: XXX"));
    assertThat(message, containsString("X-Access-Token: XXX"));
    assertThat(message, containsString("X-Trace-ID: ABC"));
}
 
示例12
@Override
public String format(final Precorrelation<HttpRequest> precorrelation) throws IOException {
    // Not logging GET/HEAD methods
    if (precorrelation.getRequest().getMethod().equalsIgnoreCase(HttpMethod.GET.name()) ||
        precorrelation.getRequest().getMethod().equalsIgnoreCase(HttpMethod.HEAD.name())) {
        return "";
    }
    final Map<String, Object> content = delegate.prepare(precorrelation);
    content.put("type","gelf");
    content.put("principal", getPrincipal());
    content.put("message", "Request message");
    content.put("tags", LOGGING_TAGS);
    return delegate.format(content);
}
 
示例13
@Override
public String format(final Correlation<HttpRequest, HttpResponse> correlation) throws IOException {
    if (correlation.getRequest().getMethod().equalsIgnoreCase(HttpMethod.GET.name()) ||
        correlation.getRequest().getMethod().equalsIgnoreCase(HttpMethod.HEAD.name())) {
        return "";
    }
    final Map<String, Object> content = delegate.prepare(correlation);
    content.put("type","gelf");
    content.put("bodyResponse", correlation.getOriginalResponse().getBodyAsString());
    content.put("principal", getPrincipal());
    content.put("message", "Response message");
    content.put("tags", LOGGING_TAGS);
    return delegate.format(content);
}
 
示例14
@Override
public void write(final Correlation correlation, final HttpRequest request,
        final HttpResponse response) throws IOException {
    final Marker marker = new AutodetectPrettyPrintingMarker("http", formatter.format(correlation, response));

    log.trace(marker, responseMessage(request, response));
}
 
示例15
@Override
public String format(
        final Precorrelation precorrelation,
        final HttpRequest request) throws IOException {

    return format(precorrelation, request, this::prepare);
}
 
示例16
private String reconstructUri(final HttpRequest request) {
    final StringBuilder builder = new StringBuilder(256);

    final String scheme = request.getScheme();
    builder.append(scheme);
    builder.append("://");
    builder.append(request.getHost());
    appendPort(request, builder);
    builder.append(request.getPath());
    appendQuery(request, builder);

    return builder.toString();
}
 
示例17
private void appendPort(final HttpRequest request, final StringBuilder builder) {
    request.getPort().ifPresent(port -> {
        final String scheme = request.getScheme();
        if (isStandardPort(scheme, port)) {
            return;
        }

        builder.append(':').append(port);
    });
}
 
示例18
private void appendQuery(final HttpRequest request, final StringBuilder builder) {
    final String query = request.getQuery();

    if (query.isEmpty()) {
        return;
    }

    builder.append('?');
    builder.append(query);
}
 
示例19
@ParameterizedTest
@MethodSource("units")
void shouldLogRequest(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "3ce91230-677b-11e5-87b7-10ddb1ee7671";
    final HttpRequest request = MockHttpRequest.create()
            .withProtocolVersion("HTTP/1.0")
            .withOrigin(REMOTE)
            .withPath("/test")
            .withQuery("limit=1")
            .withHeaders(HttpHeaders.empty()
                    .update("Accept", "application/json")
                    .update("Date", "Tue, 15 Nov 1994 08:12:31 GMT"))
            .withContentType("application/xml")
            .withBodyAsString("<action>test</action>");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$.origin", is("remote"))
            .assertThat("$.type", is("request"))
            .assertThat("$.correlation", is("3ce91230-677b-11e5-87b7-10ddb1ee7671"))
            .assertThat("$.protocol", is("HTTP/1.0"))
            .assertThat("$.remote", is("127.0.0.1"))
            .assertThat("$.method", is("GET"))
            .assertThat("$.uri", is("http://localhost/test?limit=1"))
            .assertThat("$.headers.*", hasSize(2))
            .assertThat("$.headers['Accept']", is(singletonList("application/json")))
            .assertThat("$.headers['Date']", is(singletonList("Tue, 15 Nov 1994 08:12:31 GMT")))
            .assertThat("$.body", is("<action>test</action>"));
}
 
示例20
@ParameterizedTest
@MethodSource("units")
void shouldLogRequestWithoutHeaders(final HttpLogFormatter unit) throws IOException {
    final String correlationId = "b7e7a488-682a-11e5-b527-10ddb1ee7671\n";
    final HttpRequest request = MockHttpRequest.create()
            .withPath("/test")
            .withBodyAsString("Hello, world!");

    final String json = unit.format(new SimplePrecorrelation(correlationId, systemUTC()), request);

    with(json)
            .assertThat("$", not(hasKey("headers")));
}
 
示例21
@ParameterizedTest
@MethodSource("units")
void shouldLogRequestWithoutBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("")
            .withBodyAsString("");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$", not(hasKey("body")));
}
 
示例22
@ParameterizedTest
@MethodSource("units")
void shouldEmbedJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/json")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body.name", is("Bob"));
}
 
示例23
@ParameterizedTest
@MethodSource("units")
void shouldEmbedInvalidJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/json")
            .withBodyAsString("{\"name\":\"Bob\"};");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    assertThat(json, containsString("{\"name\":\"Bob\"};"));
}
 
示例24
@ParameterizedTest
@MethodSource("units")
void shouldNotEmbedReplacedJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/json")
            .withBodyAsString("<skipped>");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body", is("<skipped>"));
}
 
示例25
@ParameterizedTest
@MethodSource("units")
void shouldEmbedCustomJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/custom+json")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body.name", is("Bob"));
}
 
示例26
@ParameterizedTest
@MethodSource("units")
void shouldEmbedCustomJsonWithParametersRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/custom+json; version=2")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body.name", is("Bob"));
}
 
示例27
@ParameterizedTest
@MethodSource("units")
void shouldNotEmbedCustomTextXmlRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("text/xml")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body", is("{\"name\":\"Bob\"}"));
}
 
示例28
@ParameterizedTest
@MethodSource("units")
void shouldNotEmbedInvalidContentTypeRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("x;y/z")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body", is("{\"name\":\"Bob\"}"));
}
 
示例29
@ParameterizedTest
@MethodSource("units")
void shouldNotEmbedCustomTextJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("text/custom+json")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body", is("{\"name\":\"Bob\"}"));
}
 
示例30
@ParameterizedTest
@MethodSource("units")
void shouldNotEmbedNonJsonRequestBody(final HttpLogFormatter unit) throws IOException {
    final HttpRequest request = MockHttpRequest.create()
            .withContentType("application/not-json")
            .withBodyAsString("{\"name\":\"Bob\"}");

    final String json = unit.format(new SimplePrecorrelation("", systemUTC()), request);

    with(json)
            .assertThat("$.body", is("{\"name\":\"Bob\"}"));
}