Skip to content
This repository has been archived by the owner on Sep 28, 2021. It is now read-only.

Look up headers in a case insensitive way #199

Merged
merged 3 commits into from
Apr 25, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.AbstractMap.SimpleEntry;
import java.util.Collections;
import java.util.Optional;
import java.util.function.BiConsumer;
Expand Down Expand Up @@ -109,7 +110,8 @@ public void testWrongMethod() throws Exception {
verify(ongoingRequest).reply(responseArgumentCaptor.capture());
Response<ByteString> reply = responseArgumentCaptor.getValue();
assertEquals(reply.status(), Status.METHOD_NOT_ALLOWED);
assertEquals(reply.headers(), Collections.singletonMap("Allow", "OPTIONS, POST"));
assertEquals(reply.headerEntries(),
Collections.singletonList(new SimpleEntry<>("Allow", "OPTIONS, POST")));
}

@Test
Expand All @@ -124,7 +126,8 @@ public void testWithMethodOptions() throws Exception {
verify(ongoingRequest).reply(responseArgumentCaptor.capture());
Response<ByteString> response = responseArgumentCaptor.getValue();
assertThat(response.status(), is(Status.NO_CONTENT));
assertThat(response.headers(), is(Collections.singletonMap("Allow", "OPTIONS, POST")));
assertThat(response.headerEntries(),
is(Collections.singletonList(new SimpleEntry<>("Allow", "OPTIONS, POST"))));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import static com.spotify.apollo.Status.NO_CONTENT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
Expand Down Expand Up @@ -168,8 +167,8 @@ class TestData {
public void httpShouldSetContentLengthFor200() throws Exception {
future.complete(Response.of(Status.OK, ByteString.of((byte) 14, (byte) 19)));

String header = getResult(Middlewares.httpPayloadSemantics(delegate)).headers().get(
"Content-Length");
String header = getResult(Middlewares.httpPayloadSemantics(delegate)).header(
"Content-Length").get();
assertThat(Integer.parseInt(header), equalTo(2));
}

Expand All @@ -192,9 +191,9 @@ public void httpShouldNotSetContentLengthOrAppendPayloadForInvalidStatusCodes()
future.complete(Response.of(status, ByteString.of((byte) 14, (byte) 19)));

Response<ByteString> result = getResult(Middlewares.httpPayloadSemantics(delegate));
String header = result.headers().get("Content-Length");
Optional<String> header = result.header("Content-Length");

assertThat("no content-length for " + status, header, is(nullValue()));
assertThat("no content-length for " + status, header, is(Optional.empty()));
assertThat("no payload for " + status, result.payload(), is(Optional.<ByteString>empty()));
}
}
Expand All @@ -204,8 +203,8 @@ public void httpShouldSetContentLengthForHeadAnd200() throws Exception {
when(request.method()).thenReturn("HEAD");
future.complete(Response.of(Status.OK, ByteString.of((byte) 14, (byte) 19)));

String header = getResult(Middlewares.httpPayloadSemantics(delegate)).headers().get(
"Content-Length");
String header = getResult(Middlewares.httpPayloadSemantics(delegate)).header(
"Content-Length").get();
assertThat(Integer.parseInt(header), equalTo(2));
}

Expand All @@ -224,8 +223,7 @@ public void contentTypeShouldAddToNonResponse() throws Exception {

String contentType = getResult(Middlewares.replyContentType("text/plain")
.apply(serializationDelegate()))
.headers()
.get("Content-Type");
.header("Content-Type").get();

assertThat(contentType, equalTo("text/plain"));
}
Expand All @@ -236,8 +234,7 @@ public void contentTypeShouldAddToResponse() throws Exception {

String contentType =
getResult(Middlewares.replyContentType("text/plain").apply(serializationDelegate()))
.headers()
.get("Content-Type");
.header("Content-Type").get();

assertThat(contentType, equalTo("text/plain"));
}
Expand Down Expand Up @@ -277,9 +274,9 @@ public void serializerShouldCopyHeadersFromResponses() throws Exception {

serializationFuture.complete(Response.forPayload(response).withHeader("X-Foo", "Fie"));

assertThat(getResult(Middlewares.serialize(serializer).apply(serializationDelegate)).headers()
.get("X-Foo"),
equalTo("Fie"));
Optional<String> header = getResult(Middlewares.serialize(serializer).apply(serializationDelegate))
.header("X-Foo");
assertThat(header.get(), equalTo("Fie"));
}

@Test
Expand All @@ -306,7 +303,7 @@ public void serializerShouldSetContentTypeIfPresent() throws Exception {
serializationFuture.complete(response);

String contentType = getResult(Middlewares.serialize(serializer).apply(serializationDelegate))
.headers().get("Content-Type");
.header("Content-Type").get();

assertThat(contentType, equalTo("coool stuff"));
}
Expand All @@ -320,10 +317,10 @@ public void serializerShouldNotSetContentTypeIfAbsent() throws Exception {

serializationFuture.complete(response);

String contentType = getResult(Middlewares.serialize(serializer).apply(serializationDelegate))
.headers().get("Content-Type");
Optional<String> contentType = getResult(Middlewares.serialize(serializer).apply(serializationDelegate))
.header("Content-Type");

assertThat(contentType, is(nullValue()));
assertThat(contentType, is(Optional.empty()));
}

@Test
Expand Down
82 changes: 82 additions & 0 deletions apollo-api/src/main/java/com/spotify/apollo/Headers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* -\-\-
* Spotify Apollo API Interfaces
* --
* Copyright (C) 2013 - 2017 Spotify AB
* --
* Licensed 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 com.spotify.apollo;

import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@AutoValue
abstract class Headers {

static Headers EMPTY = create(Collections.emptyMap());

static Headers create(Map<String, String> headers) {
final List<Map.Entry<String, String>> headersList = new ArrayList<>(headers.size());
headers.entrySet().forEach(h -> insertIfAbsent(headersList, h));
return new AutoValue_Headers(ImmutableList.copyOf(headersList));
}

public Optional<String> get(String name) {
Preconditions.checkArgument(name != null, "Header names cannot be null");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to use Objects.requireNonNull in this case - generally null arguments lead to NPEs, and it's better to use the JDK classes than Guava where feasible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Fixed


for (int i = 0; i < entries().size(); i++) {
final Map.Entry<String, String> headerEntry = entries().get(i);
if (name.equalsIgnoreCase(headerEntry.getKey())) {
return Optional.ofNullable(headerEntry.getValue());
}
}

return Optional.empty();
}

public Map<String, String> asMap() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is used a lot in apollo. Should I memoized it already in the constructor?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure; doing so would increase the memory footprint - you'd need some measurements to be sure, I guess.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll leave the optimizations for later then.

ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();
entries().forEach(headers::put);
return headers.build();
}

public abstract ImmutableList<Map.Entry<String, String>> entries();

private static void insertIfAbsent(List<Map.Entry<String, String>> headerList,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused here. Method name suggest that the value would not be overwritten (as it will be entered only if it's absent), but that's what the method does?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. I fixed the name to insertOrReplace(). Is this better?

Map.Entry<String, String> newHeader) {

// Replace existing header with new key (letter case can be overwritten) and value
for (int i = 0; i < headerList.size(); i++) {
Map.Entry<String, String> currentHeader = headerList.get(i);
if (currentHeader.getKey().equalsIgnoreCase(newHeader.getKey())) {
headerList.set(i, new SimpleImmutableEntry<>(newHeader));
return;
}
}

// No matching entry present, add new entry
headerList.add(new SimpleImmutableEntry<>(newHeader));
}

}
23 changes: 21 additions & 2 deletions apollo-api/src/main/java/com/spotify/apollo/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
package com.spotify.apollo;

import com.google.common.base.Preconditions;

import java.time.Duration;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -67,14 +69,31 @@ default Optional<String> parameter(String parameter) {

/**
* The headers of the request message.
* Deprecated in favor of {@link Request#headerEntries()}
*/
@Deprecated
Map<String, String> headers();

/**
* A header of the request message, or empty if no header with that name is found.
* All the headers of the request message.
*/
Iterable<Map.Entry<String, String>> headerEntries();


/**
* A header of the request message, looked up in a case insensitive way,
* or empty if no header with that name is found.
*/
default Optional<String> header(String name) {
return Optional.ofNullable(headers().get(name));
Preconditions.checkArgument(name != null, "Header names cannot be null");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be better to permit nulls here, and reverse the comparison below so that it would just fail to find something, rather than throw an exception for a null? I'm not sure. Either way, if nulls shouldn't be permitted, then I think we should use Objects.requireNonNull for the argument check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Talked offline about this. I will leave the check with Objects.requireNonNull


for (Map.Entry<String, String> headerEntry : headerEntries()) {
if (name.equalsIgnoreCase(headerEntry.getKey())) {
return Optional.ofNullable(headerEntry.getValue());
}
}

return Optional.empty();
}

/**
Expand Down
40 changes: 29 additions & 11 deletions apollo-api/src/main/java/com/spotify/apollo/RequestValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@

import okio.ByteString;

import static java.util.Collections.emptyMap;
import static java.util.Optional.empty;
import static java.util.Optional.of;

Expand All @@ -47,37 +46,56 @@ public static Request create(String uri) {
}

public static Request create(String uri, String method) {
return create(method, uri, parseParameters(uri), emptyMap(), empty(), empty(), empty());
return create(method, uri, parseParameters(uri), Headers.EMPTY, empty(), empty(), empty());
}

private static Request create(
String method,
String uri,
Map<String, List<String>> parameters,
Map<String, String> headers,
Headers headers,
Optional<String> service,
Optional<ByteString> payload,
Optional<Duration> ttl) {
return new AutoValue_RequestValue(
method, uri,
ImmutableMap.copyOf(parameters),
ImmutableMap.copyOf(headers),
service,
payload,
headers,
ttl);
}

// TODO Make it @Memoized once we upgrade to auto-value 1.4+
@Override
@Deprecated
public Map<String, String> headers() {
return internalHeadersImpl().asMap();
}

@Override
public Iterable<Map.Entry<String, String>> headerEntries() {
return internalHeadersImpl().entries();
}

@Override
public Optional<String> header(String name) {
return internalHeadersImpl().get(name);
}

abstract Headers internalHeadersImpl();

@Override
public abstract Optional<Duration> ttl();

@Override
public Request withUri(String uri) {
return create(method(), uri, parameters(), headers(), service(), payload(), ttl());
return create(method(), uri, parameters(), internalHeadersImpl(), service(), payload(), ttl());
}

@Override
public Request withService(String service) {
return create(method(), uri(), parameters(), headers(), of(service), payload(), ttl());
return create(method(), uri(), parameters(), internalHeadersImpl(), of(service), payload(), ttl());
}

@Override
Expand All @@ -87,24 +105,24 @@ public Request withHeader(String name, String value) {

@Override
public Request withHeaders(Map<String, String> additionalHeaders) {
Map<String, String> headers = new LinkedHashMap<>(headers());
Map<String, String> headers = new LinkedHashMap<>(internalHeadersImpl().asMap());
headers.putAll(additionalHeaders);
return create(method(), uri(), parameters(), headers, service(), payload(), ttl());
return create(method(), uri(), parameters(), Headers.create(headers), service(), payload(), ttl());
}

@Override
public Request clearHeaders() {
return create(method(), uri(), parameters(), emptyMap(), service(), payload(), ttl());
return create(method(), uri(), parameters(), Headers.EMPTY, service(), payload(), ttl());
}

@Override
public Request withPayload(ByteString payload) {
return create(method(), uri(), parameters(), headers(), service(), of(payload), ttl());
return create(method(), uri(), parameters(), internalHeadersImpl(), service(), of(payload), ttl());
}

@Override
public Request withTtl(final Duration duration) {
return create(method(), uri(), parameters(), headers(), service(), payload(), of(duration));
return create(method(), uri(), parameters(), internalHeadersImpl(), service(), payload(), of(duration));
}

private static Map<String, List<String>> parseParameters(String uri) {
Expand Down
26 changes: 26 additions & 0 deletions apollo-api/src/main/java/com/spotify/apollo/Response.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
package com.spotify.apollo;

import com.google.common.base.Preconditions;

import java.util.Map;
import java.util.Optional;

Expand All @@ -40,9 +42,32 @@ public interface Response<T> {

/**
* The response headers.
* Deprecated in favor of {@link Response#headerEntries()}
*/
@Deprecated
Map<String, String> headers();

/**
* The response headers
*/
Iterable<Map.Entry<String, String>> headerEntries();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why Iterable here? Since we're spending some effort on retaining order of headers, would it not make more sense to return a List?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was trying to be conservative and restrictive, conveying the message that this is only for iterating over all the headers. I want to prevent users from looking up keys from whatever object this method returns. Also, I didn't want to lock a specific implementation (we could change the internal implementation for a Map, etc). But I see now that I chose the wrong interface and it should have been Iterator, but maybe it's too annoying, specially since it does not have size(). What do you think would be better: Iterator or List?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Iterator is generally wrong, since they are one-use only. Iterable is better in that case.

I would still prefer List; it's still quite generic, and I feel like we have committed to retaining order. We could even specify that in the javadocs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough. Changed to List.


/**
* A header of the request message, looked up in a case insensitive way,
* or empty if no header with that name is found.
*/
default Optional<String> header(String name) {
Preconditions.checkArgument(name != null, "Header names cannot be null");

for (Map.Entry<String, String> headerEntry : headerEntries()) {
if (name.equalsIgnoreCase(headerEntry.getKey())) {
return Optional.ofNullable(headerEntry.getValue());
}
}

return Optional.empty();
}

/**
* The single payload of the response.
*/
Expand Down Expand Up @@ -119,4 +144,5 @@ static <T> Response<T> forPayload(T payload) {
static <T> Response<T> of(StatusType statusCode, T payload) {
return ResponseImpl.create(statusCode, payload);
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably remove this empty line

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}
Loading