1 // Copyright (c) 2012 The Chromium 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 "chrome/test/webdriver/commands/response.h" 6 7 #include "base/base64.h" 8 #include "base/json/json_writer.h" 9 #include "base/logging.h" 10 #include "base/values.h" 11 12 using base::DictionaryValue; 13 using base::Value; 14 15 namespace webdriver { 16 17 namespace { 18 19 // Error message taken from: 20 // http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes 21 const char kStatusKey[] = "status"; 22 const char kValueKey[] = "value"; 23 const char kMessageKey[] = "message"; 24 25 } // namespace 26 27 Response::Response() { 28 SetStatus(kSuccess); 29 SetValue(new DictionaryValue()); 30 } 31 32 Response::~Response() {} 33 34 ErrorCode Response::GetStatus() const { 35 int status; 36 if (!data_.GetInteger(kStatusKey, &status)) 37 NOTREACHED(); 38 return static_cast<ErrorCode>(status); 39 } 40 41 void Response::SetStatus(ErrorCode status) { 42 data_.SetInteger(kStatusKey, status); 43 } 44 45 const Value* Response::GetValue() const { 46 const Value* out = NULL; 47 data_.Get(kValueKey, &out); 48 return out; 49 } 50 51 void Response::SetValue(Value* value) { 52 data_.Set(kValueKey, value); 53 } 54 55 void Response::SetError(Error* error) { 56 DictionaryValue* error_dict = new DictionaryValue(); 57 error_dict->SetString(kMessageKey, error->details()); 58 59 SetStatus(error->code()); 60 SetValue(error_dict); 61 delete error; 62 } 63 64 void Response::SetField(const std::string& key, Value* value) { 65 data_.Set(key, value); 66 } 67 68 const Value* Response::GetDictionary() const { 69 return &data_; 70 } 71 72 std::string Response::ToJSON() const { 73 std::string json; 74 // The |Value| classes do not support int64 and in rare cases we need to 75 // return one. We do this by using a double and passing in the special 76 // option so that the JSONWriter doesn't add '.0' to the end and confuse 77 // the WebDriver client. 78 base::JSONWriter::WriteWithOptions( 79 &data_, base::JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION, &json); 80 return json; 81 } 82 83 } // namespace webdriver 84