blob: 471de11063803f15aa5371f09f8e75b02782f999 [file] [log] [blame]
Alex Vakulenko9cd5e272014-04-25 17:26:11 -07001// Copyright 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "buffet/http_transport_fake.h"
6
Alex Vakulenkob3aac252014-05-07 17:35:24 -07007#include <utility>
8
Alex Vakulenko8e34d392014-04-29 11:02:56 -07009#include <base/json/json_reader.h>
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070010#include <base/json/json_writer.h>
Alex Vakulenkof8545912014-04-30 12:25:19 -070011#include <base/logging.h>
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070012
Alex Vakulenko8e34d392014-04-29 11:02:56 -070013#include "buffet/bind_lambda.h"
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070014#include "buffet/http_connection_fake.h"
15#include "buffet/http_request.h"
16#include "buffet/mime_utils.h"
Alex Vakulenko96c84d32014-06-06 11:07:32 -070017#include "buffet/string_utils.h"
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070018#include "buffet/url_utils.h"
19
Alex Vakulenkoaf23b322014-05-08 16:25:45 -070020namespace buffet {
Alex Vakulenkob3aac252014-05-07 17:35:24 -070021
22using http::fake::Transport;
23using http::fake::ServerRequestResponseBase;
24using http::fake::ServerRequest;
25using http::fake::ServerResponse;
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070026
27Transport::Transport() {
28 VLOG(1) << "fake::Transport created";
29}
30
31Transport::~Transport() {
32 VLOG(1) << "fake::Transport destroyed";
33}
34
35std::unique_ptr<http::Connection> Transport::CreateConnection(
36 std::shared_ptr<http::Transport> transport,
37 const std::string& url,
38 const std::string& method,
39 const HeaderList& headers,
40 const std::string& user_agent,
41 const std::string& referer,
Alex Vakulenkob3aac252014-05-07 17:35:24 -070042 ErrorPtr* error) {
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070043 HeaderList headers_copy = headers;
44 if (!user_agent.empty()) {
45 headers_copy.push_back(std::make_pair(http::request_header::kUserAgent,
46 user_agent));
47 }
48 if (!referer.empty()) {
49 headers_copy.push_back(std::make_pair(http::request_header::kReferer,
50 referer));
51 }
52 std::unique_ptr<http::Connection> connection(
53 new http::fake::Connection(url, method, transport));
54 CHECK(connection) << "Unable to create Connection object";
Alex Vakulenkob3aac252014-05-07 17:35:24 -070055 if (!connection->SendHeaders(headers_copy, error))
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070056 connection.reset();
Alex Vakulenko8e34d392014-04-29 11:02:56 -070057 request_count_++;
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070058 return connection;
59}
60
61static inline std::string GetHandlerMapKey(const std::string& url,
62 const std::string& method) {
63 return method + ":" + url;
64}
65
66void Transport::AddHandler(const std::string& url, const std::string& method,
67 const HandlerCallback& handler) {
68 handlers_.insert(std::make_pair(GetHandlerMapKey(url, method), handler));
69}
70
Alex Vakulenko8e34d392014-04-29 11:02:56 -070071void Transport::AddSimpleReplyHandler(const std::string& url,
72 const std::string& method,
73 int status_code,
74 const std::string& reply_text,
75 const std::string& mime_type) {
76 auto handler = [status_code, reply_text, mime_type](
77 const ServerRequest& request, ServerResponse* response) {
78 response->ReplyText(status_code, reply_text, mime_type.c_str());
79 };
80 AddHandler(url, method, base::Bind(handler));
81}
82
Alex Vakulenko9cd5e272014-04-25 17:26:11 -070083Transport::HandlerCallback Transport::GetHandler(
84 const std::string& url, const std::string& method) const {
85 // First try the exact combination of URL/Method
86 auto p = handlers_.find(GetHandlerMapKey(url, method));
87 if (p != handlers_.end())
88 return p->second;
89 // If not found, try URL/*
90 p = handlers_.find(GetHandlerMapKey(url, "*"));
91 if (p != handlers_.end())
92 return p->second;
93 // If still not found, try */method
94 p = handlers_.find(GetHandlerMapKey("*", method));
95 if (p != handlers_.end())
96 return p->second;
97 // Finally, try */*
98 p = handlers_.find(GetHandlerMapKey("*", "*"));
99 return (p != handlers_.end()) ? p->second : HandlerCallback();
100}
101
102void ServerRequestResponseBase::AddData(const void* data, size_t data_size) {
103 auto bytes = reinterpret_cast<const unsigned char*>(data);
104 data_.insert(data_.end(), bytes, bytes + data_size);
105}
106
107std::string ServerRequestResponseBase::GetDataAsString() const {
108 if (data_.empty())
109 return std::string();
110 auto chars = reinterpret_cast<const char*>(data_.data());
111 return std::string(chars, data_.size());
112}
113
Alex Vakulenko8e34d392014-04-29 11:02:56 -0700114std::unique_ptr<base::DictionaryValue>
115 ServerRequestResponseBase::GetDataAsJson() const {
116 if (mime::RemoveParameters(GetHeader(request_header::kContentType)) ==
117 mime::application::kJson) {
118 auto value = base::JSONReader::Read(GetDataAsString());
119 if (value) {
120 base::DictionaryValue* dict = nullptr;
121 if (value->GetAsDictionary(&dict)) {
122 return std::unique_ptr<base::DictionaryValue>(dict);
123 } else {
124 delete value;
125 }
126 }
127 }
128 return std::unique_ptr<base::DictionaryValue>();
129}
130
Alex Vakulenko9cd5e272014-04-25 17:26:11 -0700131void ServerRequestResponseBase::AddHeaders(const HeaderList& headers) {
Alex Vakulenko96c84d32014-06-06 11:07:32 -0700132 for (const auto& pair : headers) {
Alex Vakulenko9cd5e272014-04-25 17:26:11 -0700133 if (pair.second.empty())
134 headers_.erase(pair.first);
135 else
136 headers_.insert(pair);
137 }
138}
139
140std::string ServerRequestResponseBase::GetHeader(
141 const std::string& header_name) const {
142 auto p = headers_.find(header_name);
143 return p != headers_.end() ? p->second : std::string();
144}
145
146ServerRequest::ServerRequest(const std::string& url,
147 const std::string& method) : method_(method) {
148 auto params = url::GetQueryStringParameters(url);
149 url_ = url::RemoveQueryString(url, true);
150 form_fields_.insert(params.begin(), params.end());
151}
152
153std::string ServerRequest::GetFormField(const std::string& field_name) const {
154 if (!form_fields_parsed_) {
155 std::string mime_type = mime::RemoveParameters(
156 GetHeader(request_header::kContentType));
157 if (mime_type == mime::application::kWwwFormUrlEncoded &&
158 !GetData().empty()) {
159 auto fields = data_encoding::WebParamsDecode(GetDataAsString());
160 form_fields_.insert(fields.begin(), fields.end());
161 }
162 form_fields_parsed_ = true;
163 }
164 auto p = form_fields_.find(field_name);
165 return p != form_fields_.end() ? p->second : std::string();
166}
167
168void ServerResponse::Reply(int status_code, const void* data, size_t data_size,
169 const char* mime_type) {
170 data_.clear();
171 status_code_ = status_code;
172 AddData(data, data_size);
173 AddHeaders({
Alex Vakulenko96c84d32014-06-06 11:07:32 -0700174 {response_header::kContentLength, string_utils::ToString(data_size)},
Alex Vakulenko9cd5e272014-04-25 17:26:11 -0700175 {response_header::kContentType, mime_type}
176 });
177}
178
179void ServerResponse::ReplyText(int status_code, const std::string& text,
180 const char* mime_type) {
181 Reply(status_code, text.data(), text.size(), mime_type);
182}
183
184void ServerResponse::ReplyJson(int status_code, const base::Value* json) {
185 std::string text;
186 base::JSONWriter::WriteWithOptions(json,
187 base::JSONWriter::OPTIONS_PRETTY_PRINT,
188 &text);
Alex Vakulenko8e34d392014-04-29 11:02:56 -0700189 std::string mime_type = mime::AppendParameter(mime::application::kJson,
190 mime::parameters::kCharset,
191 "utf-8");
192 ReplyText(status_code, text, mime_type.c_str());
193}
194
195void ServerResponse::ReplyJson(int status_code,
196 const http::FormFieldList& fields) {
197 base::DictionaryValue json;
Alex Vakulenko96c84d32014-06-06 11:07:32 -0700198 for (const auto& pair : fields) {
Alex Vakulenko8e34d392014-04-29 11:02:56 -0700199 json.SetString(pair.first, pair.second);
200 }
201 ReplyJson(status_code, &json);
Alex Vakulenko9cd5e272014-04-25 17:26:11 -0700202}
203
204std::string ServerResponse::GetStatusText() const {
205 static std::vector<std::pair<int, const char*>> status_text_map = {
206 {100, "Continue"},
207 {101, "Switching Protocols"},
208 {102, "Processing"},
209 {200, "OK"},
210 {201, "Created"},
211 {202, "Accepted"},
212 {203, "Non-Authoritative Information"},
213 {204, "No Content"},
214 {205, "Reset Content"},
215 {206, "Partial Content"},
216 {207, "Multi-Status"},
217 {208, "Already Reported"},
218 {226, "IM Used"},
219 {300, "Multiple Choices"},
220 {301, "Moved Permanently"},
221 {302, "Found"},
222 {303, "See Other"},
223 {304, "Not Modified"},
224 {305, "Use Proxy"},
225 {306, "Switch Proxy"},
226 {307, "Temporary Redirect"},
227 {308, "Permanent Redirect"},
228 {400, "Bad Request"},
229 {401, "Unauthorized"},
230 {402, "Payment Required"},
231 {403, "Forbidden"},
232 {404, "Not Found"},
233 {405, "Method Not Allowed"},
234 {406, "Not Acceptable"},
235 {407, "Proxy Authentication Required"},
236 {408, "Request Timeout"},
237 {409, "Conflict"},
238 {410, "Gone"},
239 {411, "Length Required"},
240 {412, "Precondition Failed"},
241 {413, "Request Entity Too Large"},
242 {414, "Request - URI Too Long"},
243 {415, "Unsupported Media Type"},
244 {429, "Too Many Requests"},
245 {431, "Request Header Fields Too Large"},
246 {500, "Internal Server Error"},
247 {501, "Not Implemented"},
248 {502, "Bad Gateway"},
249 {503, "Service Unavailable"},
250 {504, "Gateway Timeout"},
251 {505, "HTTP Version Not Supported"},
252 };
253
Alex Vakulenko96c84d32014-06-06 11:07:32 -0700254 for (const auto& pair : status_text_map) {
Alex Vakulenko9cd5e272014-04-25 17:26:11 -0700255 if (pair.first == status_code_)
256 return pair.second;
257 }
258 return std::string();
259}
Alex Vakulenkob3aac252014-05-07 17:35:24 -0700260
Alex Vakulenkoaf23b322014-05-08 16:25:45 -0700261} // namespace buffet