1 // Copyright 2013 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 "components/safe_json_parser/safe_json_parser.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "base/tuple.h"
11 #include "base/values.h"
12 #include "components/safe_json_parser/safe_json_parser_messages.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "content/public/browser/utility_process_host.h"
15 #include "grit/components_strings.h"
16 #include "ipc/ipc_message_macros.h"
17 #include "ui/base/l10n/l10n_util.h"
19 using content::BrowserThread
;
20 using content::UtilityProcessHost
;
22 namespace safe_json_parser
{
24 SafeJsonParser::SafeJsonParser(const std::string
& unsafe_json
,
25 const SuccessCallback
& success_callback
,
26 const ErrorCallback
& error_callback
)
27 : unsafe_json_(unsafe_json
),
28 success_callback_(success_callback
),
29 error_callback_(error_callback
) {
32 void SafeJsonParser::Start() {
33 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
34 BrowserThread::PostTask(
35 BrowserThread::IO
, FROM_HERE
,
36 base::Bind(&SafeJsonParser::StartWorkOnIOThread
, this));
39 SafeJsonParser::~SafeJsonParser() {
42 void SafeJsonParser::StartWorkOnIOThread() {
43 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
44 UtilityProcessHost
* host
=
45 UtilityProcessHost::Create(this, base::MessageLoopProxy::current().get());
47 l10n_util::GetStringUTF16(IDS_UTILITY_PROCESS_JSON_PARSER_NAME
));
48 host
->Send(new SafeJsonParserMsg_ParseJSON(unsafe_json_
));
51 void SafeJsonParser::OnJSONParseSucceeded(const base::ListValue
& wrapper
) {
52 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
53 const base::Value
* value
= NULL
;
54 CHECK(wrapper
.Get(0, &value
));
56 parsed_json_
.reset(value
->DeepCopy());
60 void SafeJsonParser::OnJSONParseFailed(const std::string
& error_message
) {
61 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
62 error_
= error_message
;
66 void SafeJsonParser::ReportResults() {
67 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
69 BrowserThread::PostTask(
70 BrowserThread::UI
, FROM_HERE
,
71 base::Bind(&SafeJsonParser::ReportResultOnUIThread
, this));
74 void SafeJsonParser::ReportResultOnUIThread() {
75 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
76 if (error_
.empty() && parsed_json_
) {
77 if (!success_callback_
.is_null())
78 success_callback_
.Run(parsed_json_
.Pass());
80 if (!error_callback_
.is_null())
81 error_callback_
.Run(error_
);
85 bool SafeJsonParser::OnMessageReceived(const IPC::Message
& message
) {
87 IPC_BEGIN_MESSAGE_MAP(SafeJsonParser
, message
)
88 IPC_MESSAGE_HANDLER(SafeJsonParserHostMsg_ParseJSON_Succeeded
,
90 IPC_MESSAGE_HANDLER(SafeJsonParserHostMsg_ParseJSON_Failed
,
92 IPC_MESSAGE_UNHANDLED(handled
= false)
97 } // namespace safe_json_parser