1 // Copyright 2014 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.
5 #include "content/browser/devtools/protocol/devtools_protocol_handler.h"
8 #include "base/json/json_reader.h"
14 const char kIdParam
[] = "id";
15 const char kMethodParam
[] = "method";
16 const char kParamsParam
[] = "params";
18 // JSON RPC 2.0 spec: http://www.jsonrpc.org/specification#error_object
19 const int kStatusParseError
= -32700;
20 const int kStatusInvalidRequest
= -32600;
21 const int kStatusNoSuchMethod
= -32601;
23 scoped_ptr
<base::DictionaryValue
> TakeDictionary(base::DictionaryValue
* dict
,
24 const std::string
& key
) {
25 scoped_ptr
<base::Value
> value
;
26 dict
->Remove(key
, &value
);
27 base::DictionaryValue
* result
= nullptr;
29 value
.release()->GetAsDictionary(&result
);
30 return make_scoped_ptr(result
);
35 DevToolsProtocolHandler::DevToolsProtocolHandler(const Notifier
& notifier
)
37 dispatcher_(notifier
) {
40 DevToolsProtocolHandler::~DevToolsProtocolHandler() {
43 scoped_ptr
<base::DictionaryValue
>
44 DevToolsProtocolHandler::ParseCommand(const std::string
& message
) {
45 scoped_ptr
<base::Value
> value(base::JSONReader::Read(message
));
46 if (!value
|| !value
->IsType(base::Value::TYPE_DICTIONARY
)) {
47 client_
.SendError(DevToolsProtocolClient::kNoId
,
48 Response(kStatusParseError
,
49 "Message must be in JSON format"));
53 scoped_ptr
<base::DictionaryValue
> command
=
54 make_scoped_ptr(static_cast<base::DictionaryValue
*>(value
.release()));
55 int id
= DevToolsProtocolClient::kNoId
;
56 bool ok
= command
->GetInteger(kIdParam
, &id
) && id
>= 0;
58 client_
.SendError(id
, Response(kStatusInvalidRequest
,
59 "The type of 'id' property must be number"));
64 ok
= command
->GetString(kMethodParam
, &method
);
67 Response(kStatusInvalidRequest
,
68 "The type of 'method' property must be string"));
75 void DevToolsProtocolHandler::HandleCommand(
76 scoped_ptr
<base::DictionaryValue
> command
) {
77 int id
= DevToolsProtocolClient::kNoId
;
79 command
->GetInteger(kIdParam
, &id
);
80 command
->GetString(kMethodParam
, &method
);
81 DevToolsProtocolDispatcher::CommandHandler
command_handler(
82 dispatcher_
.FindCommandHandler(method
));
83 if (command_handler
.is_null()) {
84 client_
.SendError(id
, Response(kStatusNoSuchMethod
, "No such method"));
88 command_handler
.Run(id
, TakeDictionary(command
.get(), kParamsParam
));
92 bool DevToolsProtocolHandler::HandleOptionalCommand(
93 scoped_ptr
<base::DictionaryValue
> command
) {
94 int id
= DevToolsProtocolClient::kNoId
;
96 command
->GetInteger(kIdParam
, &id
);
97 command
->GetString(kMethodParam
, &method
);
98 DevToolsProtocolDispatcher::CommandHandler
command_handler(
99 dispatcher_
.FindCommandHandler(method
));
100 if (!command_handler
.is_null())
101 return command_handler
.Run(id
, TakeDictionary(command
.get(), kParamsParam
));
105 } // namespace content