Upstream oodles of Chrome for Android code into Chromium.
[chromium-blink-merge.git] / chrome / browser / safe_json_parser.cc
blob232fdd43daed61c90439de21ebb0189410a61660
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 "chrome/grit/generated_resources.h"
9 #include "content/public/browser/browser_thread.h"
10 #include "content/public/browser/utility_process_host.h"
11 #include "ui/base/l10n/l10n_util.h"
13 using content::BrowserThread;
14 using content::UtilityProcessHost;
16 SafeJsonParser::SafeJsonParser(const std::string& unsafe_json,
17 const SuccessCallback& success_callback,
18 const ErrorCallback& error_callback)
19 : unsafe_json_(unsafe_json),
20 success_callback_(success_callback),
21 error_callback_(error_callback) {}
23 void SafeJsonParser::Start() {
24 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
25 BrowserThread::PostTask(
26 BrowserThread::IO,
27 FROM_HERE,
28 base::Bind(&SafeJsonParser::StartWorkOnIOThread, this));
31 SafeJsonParser::~SafeJsonParser() {}
33 void SafeJsonParser::StartWorkOnIOThread() {
34 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
35 UtilityProcessHost* host =
36 UtilityProcessHost::Create(this, base::MessageLoopProxy::current().get());
37 host->SetName(l10n_util::GetStringUTF16(
38 IDS_UTILITY_PROCESS_JSON_PARSER_NAME));
39 host->Send(new ChromeUtilityMsg_ParseJSON(unsafe_json_));
42 void SafeJsonParser::OnJSONParseSucceeded(const base::ListValue& wrapper) {
43 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
44 const base::Value* value = NULL;
45 CHECK(wrapper.Get(0, &value));
47 parsed_json_.reset(value->DeepCopy());
48 ReportResults();
51 void SafeJsonParser::OnJSONParseFailed(const std::string& error_message) {
52 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
53 error_ = error_message;
54 ReportResults();
57 void SafeJsonParser::ReportResults() {
58 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
60 BrowserThread::PostTask(
61 BrowserThread::UI,
62 FROM_HERE,
63 base::Bind(&SafeJsonParser::ReportResultOnUIThread, this));
66 void SafeJsonParser::ReportResultOnUIThread() {
67 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
68 if (error_.empty() && parsed_json_) {
69 if (!success_callback_.is_null())
70 success_callback_.Run(parsed_json_.Pass());
71 } else {
72 if (!error_callback_.is_null())
73 error_callback_.Run(error_);
77 bool SafeJsonParser::OnMessageReceived(const IPC::Message& message) {
78 bool handled = true;
79 IPC_BEGIN_MESSAGE_MAP(SafeJsonParser, message)
80 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Succeeded,
81 OnJSONParseSucceeded)
82 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Failed,
83 OnJSONParseFailed)
84 IPC_MESSAGE_UNHANDLED(handled = false)
85 IPC_END_MESSAGE_MAP()
86 return handled;