View Javadoc

1   /*
2    ~ Copyright 2006-2007 Nicolas De Loof.
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  package org.jmonit.web;
17  
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Map;
22  import java.util.StringTokenizer;
23  
24  import javax.servlet.http.HttpServletRequest;
25  
26  /**
27   * @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
28   */
29  public class MimeUtils
30  {
31      private static Map<String, String> mimeTypes = new HashMap<String, String>();
32  
33      // Defaults
34      static
35      {
36          mimeTypes.put( "css", "text/css" );
37          mimeTypes.put( "html", "text/html" );
38          mimeTypes.put( "xml", "text/xml" );
39          mimeTypes.put( "js", "text/javascript" );
40          mimeTypes.put( "json", "text/javascript" );
41          mimeTypes.put( "png", "image/png" );
42          mimeTypes.put( "gif", "image/gif" );
43          mimeTypes.put( "jpg", "image/jpeg" );
44          mimeTypes.put( "jpeg", "image/jpeg" );
45      }
46  
47      public static List<String> getMimeTypes( HttpServletRequest request )
48      {
49          List<String> types = getAcceptedTypes( request );
50          String uri = request.getPathInfo();
51          if ( uri == null )
52          {
53              uri = request.getRequestURI();
54          }
55          int sep = uri.lastIndexOf( '.' );
56          if ( sep > 0 )
57          {
58              String ext = uri.substring( sep + 1 );
59              String mimeType = mimeTypes.get( ext );
60              if ( mimeType != null )
61              {
62                  types.add( 0, mimeType );
63              }
64          }
65          return types;
66      }
67  
68      private static List<String> getAcceptedTypes( HttpServletRequest request )
69      {
70          List<String> mimeTypes = new ArrayList<String>();
71          String accept = request.getHeader( "accept" );
72          if ( accept.length() != 0 )
73          {
74              StringTokenizer tokenizer = new StringTokenizer( accept, "," );
75              while ( tokenizer.hasMoreTokens() )
76              {
77                  mimeTypes.add( tokenizer.nextToken() );
78              }
79          }
80          return mimeTypes;
81      }
82  }