Added better support for user IP and developer key across all APIs.
[arvados.git] / lib / google / api_client / parser.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 require 'json'
17
18 module Google
19   class APIClient
20     module Parser
21       def content_type(content_type)
22         @@content_type_mapping ||= {}
23         @@content_type_mapping[content_type] = self
24       end
25
26       def self.match_content_type(content_type)
27         # TODO(bobaman): Do this more efficiently.
28         mime_type_regexp = /^([^\/]+)(?:\/([^+]+\+)?([^;]+))?(?:;.*)?$/
29         if @@content_type_mapping[content_type]
30           # Exact match
31           return @@content_type_mapping[content_type]
32         else
33           media_type, extension, sub_type =
34             content_type.scan(mime_type_regexp)[0]
35           for pattern, parser in @@content_type_mapping
36             # We want to match on subtype first
37             pattern_media_type, pattern_extension, pattern_sub_type =
38               pattern.scan(mime_type_regexp)[0]
39             next if pattern_extension != nil
40             if media_type == pattern_media_type && sub_type == pattern_sub_type
41               return parser
42             end
43           end
44           for pattern, parser in @@content_type_mapping
45             # We failed to match on the subtype
46             # Try to match only on the media type
47             pattern_media_type, pattern_extension, pattern_sub_type =
48               pattern.scan(mime_type_regexp)[0]
49             next if pattern_extension != nil || pattern_sub_type != nil
50             if media_type == pattern_media_type
51               return parser
52             end
53           end
54         end
55         return nil
56       end
57     end
58   end
59 end