View Javadoc

1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.util;
18  
19  import java.util.Collections;
20  import java.util.LinkedHashMap;
21  import java.util.Map;
22  import java.util.Set;
23  
24  import static io.netty.util.internal.ObjectUtil.checkNotNull;
25  
26  /**
27   * Builder for immutable {@link DomainNameMapping} instances.
28   *
29   * @param <V> concrete type of value objects
30   */
31  public final class DomainNameMappingBuilder<V> {
32  
33      private final V defaultValue;
34      private final Map<String, V> map;
35  
36      /**
37       * Constructor with default initial capacity of the map holding the mappings
38       *
39       * @param defaultValue the default value for {@link DomainNameMapping#map(String)} to return
40       *                     when nothing matches the input
41       */
42      public DomainNameMappingBuilder(V defaultValue) {
43          this(4, defaultValue);
44      }
45  
46      /**
47       * Constructor with initial capacity of the map holding the mappings
48       *
49       * @param initialCapacity initial capacity for the internal map
50       * @param defaultValue    the default value for {@link DomainNameMapping#map(String)} to return
51       *                        when nothing matches the input
52       */
53      public DomainNameMappingBuilder(int initialCapacity, V defaultValue) {
54          this.defaultValue = checkNotNull(defaultValue, "defaultValue");
55          map = new LinkedHashMap<String, V>(initialCapacity);
56      }
57  
58      /**
59       * Adds a mapping that maps the specified (optionally wildcard) host name to the specified output value.
60       * Null values are forbidden for both hostnames and values.
61       * <p>
62       * <a href="http://en.wikipedia.org/wiki/Wildcard_DNS_record">DNS wildcard</a> is supported as hostname.
63       * For example, you can use {@code *.netty.io} to match {@code netty.io} and {@code downloads.netty.io}.
64       * </p>
65       *
66       * @param hostname the host name (optionally wildcard)
67       * @param output   the output value that will be returned by {@link DomainNameMapping#map(String)}
68       *                 when the specified host name matches the specified input host name
69       */
70      public DomainNameMappingBuilder<V> add(String hostname, V output) {
71          map.put(checkNotNull(hostname, "hostname"), checkNotNull(output, "output"));
72          return this;
73      }
74  
75      /**
76       * Creates a new instance of immutable {@link DomainNameMapping}
77       * Attempts to add new mappings to the result object will cause {@link UnsupportedOperationException} to be thrown
78       *
79       * @return new {@link DomainNameMapping} instance
80       */
81      public DomainNameMapping<V> build() {
82          return new ImmutableDomainNameMapping<V>(defaultValue, map);
83      }
84  
85      /**
86       * Immutable mapping from domain name pattern to its associated value object.
87       * Mapping is represented by two arrays: keys and values. Key domainNamePatterns[i] is associated with values[i].
88       *
89       * @param <V> concrete type of value objects
90       */
91      private static final class ImmutableDomainNameMapping<V> extends DomainNameMapping<V> {
92          private static final String REPR_HEADER = "ImmutableDomainNameMapping(default: ";
93          private static final String REPR_MAP_OPENING = ", map: {";
94          private static final String REPR_MAP_CLOSING = "})";
95          private static final int REPR_CONST_PART_LENGTH =
96              REPR_HEADER.length() + REPR_MAP_OPENING.length() + REPR_MAP_CLOSING.length();
97  
98          private final String[] domainNamePatterns;
99          private final V[] values;
100         private final Map<String, V> map;
101 
102         @SuppressWarnings("unchecked")
103         private ImmutableDomainNameMapping(V defaultValue, Map<String, V> map) {
104             super(null, defaultValue);
105 
106             Set<Map.Entry<String, V>> mappings = map.entrySet();
107             int numberOfMappings = mappings.size();
108             domainNamePatterns = new String[numberOfMappings];
109             values = (V[]) new Object[numberOfMappings];
110 
111             final Map<String, V> mapCopy = new LinkedHashMap<String, V>(map.size());
112             int index = 0;
113             for (Map.Entry<String, V> mapping : mappings) {
114                 final String hostname = normalizeHostname(mapping.getKey());
115                 final V value = mapping.getValue();
116                 domainNamePatterns[index] = hostname;
117                 values[index] = value;
118                 mapCopy.put(hostname, value);
119                 ++index;
120             }
121 
122             this.map = Collections.unmodifiableMap(mapCopy);
123         }
124 
125         @Override
126         @Deprecated
127         public DomainNameMapping<V> add(String hostname, V output) {
128             throw new UnsupportedOperationException(
129                 "Immutable DomainNameMapping does not support modification after initial creation");
130         }
131 
132         @Override
133         public V map(String hostname) {
134             if (hostname != null) {
135                 hostname = normalizeHostname(hostname);
136 
137                 int length = domainNamePatterns.length;
138                 for (int index = 0; index < length; ++index) {
139                     if (matches(domainNamePatterns[index], hostname)) {
140                         return values[index];
141                     }
142                 }
143             }
144 
145             return defaultValue;
146         }
147 
148         @Override
149         public Map<String, V> asMap() {
150             return map;
151         }
152 
153         @Override
154         public String toString() {
155             String defaultValueStr = defaultValue.toString();
156 
157             int numberOfMappings = domainNamePatterns.length;
158             if (numberOfMappings == 0) {
159                 return REPR_HEADER + defaultValueStr + REPR_MAP_OPENING + REPR_MAP_CLOSING;
160             }
161 
162             String pattern0 = domainNamePatterns[0];
163             String value0 = values[0].toString();
164             int oneMappingLength = pattern0.length() + value0.length() + 3; // 2 for separator ", " and 1 for '='
165             int estimatedBufferSize = estimateBufferSize(defaultValueStr.length(), numberOfMappings, oneMappingLength);
166 
167             StringBuilder sb = new StringBuilder(estimatedBufferSize)
168                 .append(REPR_HEADER).append(defaultValueStr).append(REPR_MAP_OPENING);
169 
170             appendMapping(sb, pattern0, value0);
171             for (int index = 1; index < numberOfMappings; ++index) {
172                 sb.append(", ");
173                 appendMapping(sb, index);
174             }
175 
176             return sb.append(REPR_MAP_CLOSING).toString();
177         }
178 
179         /**
180          * Estimates the length of string representation of the given instance:
181          * est = lengthOfConstantComponents + defaultValueLength + (estimatedMappingLength * numOfMappings) * 1.10
182          *
183          * @param defaultValueLength     length of string representation of {@link #defaultValue}
184          * @param numberOfMappings       number of mappings the given instance holds,
185          *                               e.g. {@link #domainNamePatterns#length}
186          * @param estimatedMappingLength estimated size taken by one mapping
187          * @return estimated length of string returned by {@link #toString()}
188          */
189         private static int estimateBufferSize(int defaultValueLength,
190                                               int numberOfMappings,
191                                               int estimatedMappingLength) {
192             return REPR_CONST_PART_LENGTH + defaultValueLength
193                 + (int) (estimatedMappingLength * numberOfMappings * 1.10);
194         }
195 
196         private StringBuilder appendMapping(StringBuilder sb, int mappingIndex) {
197             return appendMapping(sb, domainNamePatterns[mappingIndex], values[mappingIndex].toString());
198         }
199 
200         private static StringBuilder appendMapping(StringBuilder sb, String domainNamePattern, String value) {
201             return sb.append(domainNamePattern).append('=').append(value);
202         }
203     }
204 }