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 "chrome/browser/safe_json_parser.h"
7 #include "chrome/common/chrome_utility_messages.h"
8 #include "content/public/browser/browser_thread.h"
9 #include "content/public/browser/utility_process_host.h"
11 using content::BrowserThread
;
12 using content::UtilityProcessHost
;
14 SafeJsonParser::SafeJsonParser(const std::string
& unsafe_json
,
15 const SuccessCallback
& success_callback
,
16 const ErrorCallback
& error_callback
)
17 : unsafe_json_(unsafe_json
),
18 success_callback_(success_callback
),
19 error_callback_(error_callback
) {}
21 void SafeJsonParser::Start() {
22 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
23 BrowserThread::PostTask(
26 base::Bind(&SafeJsonParser::StartWorkOnIOThread
, this));
29 SafeJsonParser::~SafeJsonParser() {}
31 void SafeJsonParser::StartWorkOnIOThread() {
32 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
33 UtilityProcessHost
* host
=
34 UtilityProcessHost::Create(this, base::MessageLoopProxy::current().get());
36 host
->Send(new ChromeUtilityMsg_ParseJSON(unsafe_json_
));
39 void SafeJsonParser::OnJSONParseSucceeded(const base::ListValue
& wrapper
) {
40 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
41 const Value
* value
= NULL
;
42 CHECK(wrapper
.Get(0, &value
));
44 parsed_json_
.reset(value
->DeepCopy());
48 void SafeJsonParser::OnJSONParseFailed(const std::string
& error_message
) {
49 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
50 error_
= error_message
;
54 void SafeJsonParser::ReportResults() {
55 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
57 BrowserThread::PostTask(
60 base::Bind(&SafeJsonParser::ReportResultOnUIThread
, this));
63 void SafeJsonParser::ReportResultOnUIThread() {
64 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
65 if (error_
.empty() && parsed_json_
) {
66 if (!success_callback_
.is_null())
67 success_callback_
.Run(parsed_json_
.Pass());
69 if (!error_callback_
.is_null())
70 error_callback_
.Run(error_
);
74 bool SafeJsonParser::OnMessageReceived(const IPC::Message
& message
) {
76 IPC_BEGIN_MESSAGE_MAP(SafeJsonParser
, message
)
77 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Succeeded
,
79 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Failed
,
81 IPC_MESSAGE_UNHANDLED(handled
= false)