1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.net;
18
19import com.google.common.base.Ascii;
20import com.google.common.base.Joiner;
21import com.google.common.base.Splitter;
22import com.google.common.collect.ImmutableSet;
23import com.google.common.collect.Lists;
24
25import junit.framework.TestCase;
26
27import java.lang.reflect.Field;
28import java.util.List;
29
30/**
31 * Tests for the HttpHeaders class.
32 *
33 * @author Kurt Aflred Kluever
34 */
35public class HttpHeadersTest extends TestCase {
36  public void testConstantNameMatchesString() throws Exception {
37    for (Field field : HttpHeaders.class.getDeclaredFields()) {
38      /*
39       * Coverage mode generates synthetic fields.  If we ever add private
40       * fields, they will cause similar problems, and we may want to switch
41       * this check to isAccessible().
42       */
43      if (!field.isSynthetic()) {
44        assertEquals(upperToHttpHeaderName(field.getName()), field.get(null));
45      }
46    }
47  }
48
49  private static final ImmutableSet<String> UPPERCASE_ACRONYMS = ImmutableSet.of(
50      "ID", "DNT", "GFE", "IP", "MD5", "P3P", "TE", "UID", "URL", "WWW", "XSS");
51
52  private static final Splitter SPLITTER = Splitter.on('_');
53  private static final Joiner JOINER = Joiner.on('-');
54
55  private static String upperToHttpHeaderName(String constantName) {
56    // Special case some of the weird HTTP Header names...
57    if (constantName.equals("ETAG")) {
58      return "ETag";
59    }
60
61    List<String> parts = Lists.newArrayList();
62    for (String part : SPLITTER.split(constantName)) {
63      if (!UPPERCASE_ACRONYMS.contains(part)) {
64        part = part.charAt(0) + Ascii.toLowerCase(part.substring(1));
65      }
66      parts.add(part);
67    }
68    return JOINER.join(parts);
69  }
70}
71