001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.encoders;
014
015import static org.apache.juneau.internal.CollectionUtils.*;
016
017import java.util.*;
018import java.util.concurrent.*;
019
020import org.apache.juneau.http.*;
021
022/**
023 * Represents the group of {@link Encoder encoders} keyed by codings.
024 * 
025 * <h5 class='topic'>Description</h5>
026 * 
027 * Maintains a set of encoders and the codings that they can handle.
028 * 
029 * <p>
030 * The {@link #getEncoderMatch(String)} and {@link #getEncoder(String)} methods are then used to find appropriate
031 * encoders for specific <code>Accept-Encoding</code> and <code>Content-Encoding</code> header values.
032 * 
033 * <h5 class='topic'>Match ordering</h5>
034 * 
035 * Encoders are matched against <code>Accept-Encoding</code> strings in the order they exist in this group.
036 * 
037 * <p>
038 * Adding new entries will cause the entries to be prepended to the group.
039 * This allows for previous encoders to be overridden through subsequent calls.
040 * 
041 * <p>
042 * For example, calling <code>groupBuilder.append(E1.<jk>class</jk>,E2.<jk>class</jk>).append(E3.<jk>class</jk>,
043 * E4.<jk>class</jk>)</code> will result in the order <code>E3, E4, E1, E2</code>.
044 * 
045 * <h5 class='section'>Example:</h5>
046 * <p class='bcode'>
047 *    <jc>// Create an encoder group with support for gzip compression.</jc>
048 *    EncoderGroup g = EncoderGroup.<jsm>create</jsm>().append(GzipEncoder.<jk>class</jk>).build();
049 * 
050 *    <jc>// Should return "gzip"</jc>
051 *    String matchedCoding = g.findMatch(<js>"compress;q=1.0, gzip;q=0.8, identity;q=0.5, *;q=0"</js>);
052 * 
053 *    <jc>// Get the encoder</jc>
054 *    IEncoder encoder = g.getEncoder(matchedCoding);
055 * </p>
056 */
057public final class EncoderGroup {
058
059   // Maps Accept-Encoding headers to matching encoders.
060   private final ConcurrentHashMap<String,EncoderMatch> cache = new ConcurrentHashMap<>();
061
062   private final String[] encodings;
063   private final List<String> encodingsList;
064   private final Encoder[] encodingsEncoders;
065   private final List<Encoder> encoders;
066
067   /**
068    * Instantiates a new clean-slate {@link EncoderGroupBuilder} object.
069    * 
070    * <p>
071    * This is equivalent to simply calling <code><jk>new</jk> EncoderGroupBuilder()</code>.
072    * 
073    * @return A new {@link EncoderGroupBuilder} object.
074    */
075   public static EncoderGroupBuilder create() {
076      return new EncoderGroupBuilder();
077   }
078
079   /**
080    * Returns a builder that's a copy of the settings on this encoder group.
081    * 
082    * @return A new {@link EncoderGroupBuilder} initialized to this group.
083    */
084   public EncoderGroupBuilder builder() {
085      return new EncoderGroupBuilder(this);
086   }
087   
088   /**
089    * Constructor
090    * 
091    * @param encoders The encoders to add to this group.
092    */
093   public EncoderGroup(Encoder[] encoders) {
094      this.encoders = immutableList(encoders);
095
096      List<String> lc = new ArrayList<>();
097      List<Encoder> l = new ArrayList<>();
098      for (Encoder e : encoders) {
099         for (String c: e.getCodings()) {
100            lc.add(c);
101            l.add(e);
102         }
103      }
104
105      this.encodings = lc.toArray(new String[lc.size()]);
106      this.encodingsList = unmodifiableList(lc);
107      this.encodingsEncoders = l.toArray(new Encoder[l.size()]);
108   }
109
110   /**
111    * Returns the coding string for the matching encoder that can handle the specified <code>Accept-Encoding</code>
112    * or <code>Content-Encoding</code> header value.
113    * 
114    * <p>
115    * Returns <jk>null</jk> if no encoders can handle it.
116    * 
117    * <p>
118    * This method is fully compliant with the RFC2616/14.3 and 14.11 specifications.
119    * 
120    * @param acceptEncoding The <code>Accept-Encoding</code> or <code>Content-Encoding</code> value.
121    * @return The coding value (e.g. <js>"gzip"</js>).
122    */
123   public EncoderMatch getEncoderMatch(String acceptEncoding) {
124      EncoderMatch em = cache.get(acceptEncoding);
125      if (em != null)
126         return em;
127
128      AcceptEncoding ae = AcceptEncoding.forString(acceptEncoding);
129      int match = ae.findMatch(encodings);
130
131      if (match >= 0) {
132         em = new EncoderMatch(encodings[match], encodingsEncoders[match]);
133         cache.putIfAbsent(acceptEncoding, em);
134      }
135
136      return cache.get(acceptEncoding);
137   }
138
139   /**
140    * Returns the encoder registered with the specified coding (e.g. <js>"gzip"</js>).
141    * 
142    * @param encoding The coding string.
143    * @return The encoder, or <jk>null</jk> if encoder isn't registered with that coding.
144    */
145   public Encoder getEncoder(String encoding) {
146      EncoderMatch em = getEncoderMatch(encoding);
147      return (em == null ? null : em.getEncoder());
148   }
149
150   /**
151    * Returns the set of codings supported by all encoders in this group.
152    * 
153    * @return An unmodifiable list of codings supported by all encoders in this group.  Never <jk>null</jk>.
154    */
155   public List<String> getSupportedEncodings() {
156      return encodingsList;
157   }
158
159   /**
160    * Returns the encoders in this group.
161    * 
162    * @return An unmodifiable list of encoders in this group.
163    */
164   public List<Encoder> getEncoders() {
165      return encoders;
166   }
167}