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

Commit

Permalink
Merge pull request #199 from martina-if/case-insensitive-headers
Browse files Browse the repository at this point in the history
Look up headers in a case insensitive way
  • Loading branch information
martina-if committed Apr 25, 2017
2 parents 4d9e653 + 2975a92 commit ba73aa9
Show file tree
Hide file tree
Showing 18 changed files with 436 additions and 65 deletions.
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.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.Objects;
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 -> insertOrReplace(headersList, h));
return new AutoValue_Headers(ImmutableList.copyOf(headersList));
}

public Optional<String> get(String name) {
Objects.requireNonNull(name, "Header names cannot be null");

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() {
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 insertOrReplace(List<Map.Entry<String, String>> headerList,
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));
}

}
22 changes: 20 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 @@ -22,6 +22,7 @@
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import okio.ByteString;
Expand Down Expand Up @@ -67,14 +68,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.
*/
List<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));
Objects.requireNonNull(name, "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();
}

/**
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 List<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
25 changes: 25 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,7 +19,9 @@
*/
package com.spotify.apollo;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Nullable;
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
*/
List<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) {
Objects.requireNonNull(name, "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
Loading

0 comments on commit ba73aa9

Please sign in to comment.