1 /*
2  *  Licensed to the Apache Software Foundation (ASF) under one or more
3  *  contributor license agreements.  See the NOTICE file distributed with
4  *  this work for additional information regarding copyright ownership.
5  *  The ASF licenses this file to You under the Apache License, Version 2.0
6  *  (the "License"); you may not use this file except in compliance with
7  *  the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  */

17 package org.apache.tomcat.util.http.parser;
18
19 import java.io.IOException;
20 import java.io.StringReader;
21
22 import org.apache.tomcat.util.collections.ConcurrentCache;
23
24 /**
25  * Caches the results of parsing content-type headers.
26  */

27 public class MediaTypeCache {
28
29     private final ConcurrentCache<String,String[]> cache;
30
31     public MediaTypeCache(int size) {
32         cache = new ConcurrentCache<>(size);
33     }
34
35     /**
36      * Looks in the cache and returns the cached value if one is present. If no
37      * match exists in the cache, a new parser is created, the input parsed and
38      * the results placed in the cache and returned to the user.
39      *
40      * @param input The content-type header value to parse
41      * @return      The results are provided as a two element String array. The
42      *                  first element is the media type less the charset and
43      *                  the second element is the charset
44      */

45     public String[] parse(String input) {
46         String[] result = cache.get(input);
47
48         if (result != null) {
49             return result;
50         }
51
52         MediaType m = null;
53         try {
54             m = MediaType.parseMediaType(new StringReader(input));
55         } catch (IOException e) {
56             // Ignore - return null
57         }
58         if (m != null) {
59             result = new String[] {m.toStringNoCharset(), m.getCharset()};
60             cache.put(input, result);
61         }
62
63         return result;
64     }
65 }
66