View Javadoc

1   package com.atlassian.gzipfilter.util;
2   
3   /**
4    * Extracts the type and encoding from an HTTP Content-Type header.
5    *
6    * @author Scott Farquhar
7    */
8   public class HttpContentType {
9   
10      private final String type;
11      private final String encoding;
12  
13      public HttpContentType(String fullValue) {
14          // this is the content type + charset. eg: text/html;charset=UTF-8
15          int offset = fullValue.lastIndexOf("charset=");
16          encoding = offset != -1 ? extractContentTypeValue(fullValue, offset + 8) : null;
17          type = extractContentTypeValue(fullValue, 0);
18      }
19  
20      private String extractContentTypeValue(String type, int startIndex) {
21          if (startIndex < 0)
22              return null;
23  
24          // Skip over any leading spaces
25          while (startIndex < type.length() && type.charAt(startIndex) == ' ') startIndex++;
26  
27          if (startIndex >= type.length()) {
28              return null;
29          }
30  
31          int endIndex = startIndex;
32  
33          if (type.charAt(startIndex) == '"') {
34              startIndex++;
35              endIndex = type.indexOf('"', startIndex);
36              if (endIndex == -1)
37                  endIndex = type.length();
38          } else {
39              // Scan through until we hit either  the end of the string or a
40              // special character (as defined in RFC-2045). Note that we ignore '/'
41              // since we want to capture it as part of the value.
42              char ch;
43              while (endIndex < type.length() && (ch = type.charAt(endIndex)) != ' ' && ch != ';'
44                      && ch != '(' && ch != ')' && ch != '[' && ch != ']' && ch != '<' && ch != '>'
45                      && ch != ':' && ch != ',' && ch != '=' && ch != '?' && ch != '@' && ch != '"'
46                      && ch != '\\') endIndex++;
47          }
48          return type.substring(startIndex, endIndex);
49      }
50  
51      public String getType() {
52          return type;
53      }
54  
55      public String getEncoding() {
56          return encoding;
57      }
58  }