View Javadoc

1   /**
2    * Copyright (C) 2005-2009 Alfresco Software Limited.
3    *
4    * This file is part of the Spring Surf Extension project.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *  http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.springframework.extensions.webscripts;
20  
21  
22  /**
23   * Map between media type and format
24   * 
25   * This class is immutable.
26   * 
27   * @author davidc
28   */
29  public final class NegotiatedFormat
30  {
31      final private MediaType mediaType;
32      final private String format;
33      
34      /**
35       * Construct
36       * 
37       * @param mediaType
38       * @param format
39       */
40      public NegotiatedFormat(MediaType mediaType, String format)
41      {
42          this.mediaType = mediaType;
43          this.format = format;
44      }
45  
46      /**
47       * @return  media type
48       */
49      public MediaType getMediaType()
50      {
51          return mediaType;
52      }
53      
54      /**
55       * @return  format
56       */
57      public String getFormat()
58      {
59          return format;
60      }
61      
62      /**
63       * Negotiate Format - given a list of accepted media types, return the format that's
64       * most suitable
65       * 
66       * @param accept  comma-seperated list of accepted media types
67       * @param negotiatedFormats  list of available formats
68       * @return  most suitable format (or null, if none)
69       */
70      public static String negotiateFormat(String accept, NegotiatedFormat[] negotiatedFormats)
71      {
72          String format = null;
73          float match = 0.0f;
74          String[] acceptTypes = accept.split(",");
75          for (String acceptType : acceptTypes)
76          {
77              MediaType acceptMediaType = new MediaType(acceptType);
78              for (NegotiatedFormat negotiatedFormat : negotiatedFormats)
79              {
80                  float negotiatedMatch = negotiatedFormat.getMediaType().compare(acceptMediaType);
81                  if (negotiatedMatch > match)
82                  {
83                      match = negotiatedMatch;
84                      format = negotiatedFormat.getFormat();
85                  }
86              }
87          }
88          return format;
89      }
90  }